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

后端 未结 3 1750
清歌不尽
清歌不尽 2021-02-12 02:36

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

3条回答
  •  一生所求
    2021-02-12 03:22

    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))
    

提交回复
热议问题