kotlininstanceofkotest

kotlin-test: How to test for a specific type like: "is y instance of X"


How to test if a val/var is of an expected type?

Is there something I am missing in Kotlin Test, like:

value shouldBe instanceOf<ExpectedType>()

Here is how I implemented it:

inline fun <reified T> instanceOf(): Matcher<Any> {
    return object : Matcher<Any> {
        override fun test(value: Any) =
                Result(value is T, "Expected an instance of type: ${T::class} \n Got: ${value::class}", "")

    }
}

Solution

  • In KotlinTest, a lot is about proper spacing :) You can use should to get access to a variety of built-in matchers.

    import io.kotlintest.matchers.beInstanceOf
    import io.kotlintest.should
    
    value should beInstanceOf<Type>()
    

    There is also an alternative syntax:

    value.shouldBeInstanceOf<Type>()
    

    See here for more information.