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

问题描述 投票:17回答:3

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

如何编译以下内容?

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

目前我的IDE,InteliJ强调这是一个编译错误,说它在)之后期待一个is

unit-testing junit kotlin hamcrest
3个回答
29
投票

使用is关键字导入时,可以将Is(比如as)别名。

E.g:

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

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


27
投票

在Kotlin,is是一个保守的词。要解决此问题,您需要使用反引号来转义代码,因此以下内容将允许您编译代码:

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

3
投票

正如其他人指出的那样,在Kotlin中,is是一个保留词(见Type Checks)。但这对Hamcrest来说不是一个大问题,因为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))
© www.soinside.com 2019 - 2024. All rights reserved.