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

£可爱£侵袭症+ 提交于 2019-12-21 03:14:07

问题


I want to write a unit test for my Kotlin code and use junit/hamcrest matchers, I want to use the is method, but it is a reserved word in Kotlin.

How can I get the following to compile?

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

Currently my IDE, InteliJ is highlighting that as a compilation error, saying it is expecting a ) after is?


回答1:


In Kotlin, is is a reserved word . To get around this you need to escape the code using backticks, so the following will allow you to compile the code:

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



回答2:


You can alias is (say to Is) when you import using the as keyword.

E.g:

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

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




回答3:


As others pointed out, in Kotlin, is is a reserved word (see Type Checks). But it's not a big problem with Hamcrest since is function is just a decorator. It's used for better code readability, but it's not required for proper functioning.

You are free to use a shorter Kotlin-friendly expression.

  1. equality:

    assertThat(cheese, equalTo(smelly))
    

    instead of:

    assertThat(cheese, `is`(equalTo(smelly)))
    
  2. matcher decorator:

    assertThat(cheeseBasket, empty())
    

    instead of:

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

Another frequently used Hamcrest matcher is a type-check like

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

It's deprecated and it's not Kotlin-friendly. Instead, you're advised to use one of the following:

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


来源:https://stackoverflow.com/questions/40025927/how-to-compile-kotlin-unit-test-code-that-uses-hamcrest-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!