Vincent Mimoun-Prat
Vincent Mimoun-Prat

Reputation: 28541

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

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

Upvotes: 23

Views: 22936

Answers (5)

Balu
Balu

Reputation: 689

Since Kotlin 1.5 you can also do this with the assertions of Kotlin, withtout using JUnit. This is prettier than the example posted in the question.

Dependency:

    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-test</artifactId>
        <version>${kotlin.version}</version>
    </dependency>

Assertion example:

import kotlin.test.assertIs

assertIs<Bar>(foo)

Upvotes: 10

Gremi64
Gremi64

Reputation: 1677

You can use assertInstanceOf doc here

And it become as simple as :

import org.junit.jupiter.api.Assertions.assertInstanceOf

assertInstanceOf(Bar::class.java, foo)

Upvotes: 1

Robert Stoll
Robert Stoll

Reputation: 401

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

Upvotes: 2

ledniov
ledniov

Reputation: 2382

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

Upvotes: 32

Kevin Robatel
Kevin Robatel

Reputation: 8386

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

Documentation: https://kotlinlang.org/docs/reference/java-interop.html#getclass

Upvotes: 4

Related Questions