我想为我的Kotlin代码编写单元测试并使用junit / hamcrest匹配器,我想使用is
方法,但它是Kotlin中的保留字。
如何编译以下内容?
class testExample{
@Test fun example(){
assertThat(1, is(equalTo(1))
}
}
目前我的IDE,InteliJ强调这是一个编译错误,说它在)
之后期待一个is
?
使用is
关键字导入时,可以将Is
(比如as
)别名。
E.g:
import org.hamcrest.CoreMatchers.`is` as Is
在Kotlin,is
是一个保守的词。要解决此问题,您需要使用反引号来转义代码,因此以下内容将允许您编译代码:
class testExample{
@Test fun example(){
assertThat(1, `is`(equalTo(1))
}
}
正如其他人指出的那样,在Kotlin中,is
是一个保留词(见Type Checks)。但这对Hamcrest来说不是一个大问题,因为is
函数只是一个装饰者。它用于更好的代码可读性,但它不是正常运行所必需的。
您可以自由使用更短的Kotlin友好表达。
assertThat(cheese, equalTo(smelly))
代替:
assertThat(cheese, `is`(equalTo(smelly)))
assertThat(cheeseBasket, empty())
代替:
assertThat(cheeseBasket, `is`(empty()))
另一个经常使用的Hamcrest匹配器是类型检查
assertThat(cheese, `is`(Cheddar.class))
它被弃用了,它不是Kotlin友好的。相反,建议您使用以下之一:
assertThat(cheese, isA(Cheddar.class))
assertThat(cheese, instanceOf(Cheddar.class))