Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin for assertThat(foo, instanceOf(Bar.class))

Tags:

junit

kotlin

How would you write assertThat(foo, instanceOf(Bar.class)) with Kotlin?

Seems that it does not like the .class

I would like to go for an assertion which is a bit more "precise" than just an assertTrue(foo is Bar) if possible

like image 992
Vincent Mimoun-Prat Avatar asked Jul 06 '17 09:07

Vincent Mimoun-Prat


2 Answers

Bar::class returns instance of KClass, which is Kotlin equivalent of Java's Class.

instanceOf method requires Class instance, not KClass, so you have to convert it using Bar::class.java.

So your assertion should be like:

assertThat(foo, instanceOf(Bar::class.java))

More info about Java interop you can find here.

Also you can have a look at Hamkrest library which may add more fluency to your assertions:

assert.that(foo, isA<Bar>())
like image 101
ledniov Avatar answered Sep 21 '22 13:09

ledniov


You could use Atrium (https://atriumlib.org) and write the following

assertThat(foo).isA<Bar>{} 

And in case you want to assert more about foo, say Bar has a val baz: Int, then you can write the following

assertThat(foo).isA<Bar> { 
  property(subject::baz).isSmallerThan(41) 
}
like image 36
Robert Stoll Avatar answered Sep 22 '22 13:09

Robert Stoll