Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    }
}
like image 306
Chriss Avatar asked Apr 29 '19 11:04

Chriss


1 Answers

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.

like image 98
TheOperator Avatar answered Sep 21 '22 21:09

TheOperator