如何编译使用 hamcrest 的 Kotlin 单元测试代码 'is'

How to compile Kotlin unit test code that uses hamcrest 'is'

我想为我的 Kotlin 代码编写单元测试并使用 junit/hamcrest 匹配器,我想使用 is 方法,但它是 Kotlin 中的保留字。

如何编译以下内容?

class testExample{
  @Test fun example(){
    assertThat(1, is(equalTo(1))
  }
}

目前我的 IDE,InteliJ 将其突出显示为编译错误,并表示它在 is?

之后期待 )

在 Kotlin 中,is 是一个保留字。要解决这个问题,您需要使用反引号对代码进行转义,因此您可以通过以下代码编译代码:

class testExample{
  @Test fun example(){
    assertThat(1, `is`(equalTo(1))
  }
}

您可以在导入时使用 as 关键字将 is 别名为 Is(例如)。

例如:

 import org.hamcrest.CoreMatchers.`is` as Is

https://kotlinlang.org/docs/reference/packages.html

正如其他人指出的那样,在 Kotlin 中,is 是一个保留字(参见 Type Checks). But it's not a big problem with Hamcrest since is 函数只是一个装饰器。它用于更好的代码可读性,但它不是正常运行所必需的。

您可以自由使用更短的 Kotlin 友好表达式。

  1. 平等:

    assertThat(cheese, equalTo(smelly))
    

    而不是:

    assertThat(cheese, `is`(equalTo(smelly)))
    
  2. 匹配器装饰器:

    assertThat(cheeseBasket, empty())
    

    而不是:

    assertThat(cheeseBasket, `is`(empty()))
    

另一个经常使用的 Hamcrest 匹配器是类型检查,例如

assertThat(cheese, `is`(Cheddar.class))

它已被弃用,并且对 Kotlin 不友好。相反,建议您使用以下其中一项:

assertThat(cheese, isA(Cheddar.class))
assertThat(cheese, instanceOf(Cheddar.class))