Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 954
thecoshman Avatar asked Oct 13 '16 16:10

thecoshman


People also ask

What is Hamcrest in testing?

Hamcrest is a widely used framework for unit testing in the Java world. Hamcrest target is to make your tests easier to write and read. For this, it provides additional matcher classes which can be used in test for example written with JUnit. You can also define custom matcher implementations.

Does JUnit include Hamcrest?

Hamcrest is the well-known framework used for unit testing in the Java ecosystem. It's bundled in JUnit and simply put, it uses existing predicates – called matcher classes – for making assertions.

Is assertThat actual is Equalto expected ))) a valid Hamcrest assert statement?

assertEquals() is the method of Assert class in JUnit, assertThat() belongs to Matchers class of Hamcrest. Both methods assert the same thing; however, hamcrest matcher is more human-readable. As you see, it is like an English sentence “Assert that actual is equal to the expected value”.


1 Answers

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

E.g:

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

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

like image 63
David Soroko Avatar answered Oct 27 '22 16:10

David Soroko