kotlin-test:如何测试特定类型,例如:“是 X 的 y 实例”

Chr*_*iss 4 instanceof kotlin kotlintest

如何测试 val/var 是否属于预期类型?

我在 Kotlin 测试中缺少什么,例如:

value shouldBe instanceOf<ExpectedType>()
Run Code Online (Sandbox Code Playgroud)

这是我如何实施它:

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

    }
}
Run Code Online (Sandbox Code Playgroud)

The*_*tor 11

在 KotlinTest 中,很多都与适当的间距有关 :) 您可以使用should来访问各种内置匹配器。

import io.kotlintest.matchers.beInstanceOf
import io.kotlintest.should

value should beInstanceOf<Type>()
Run Code Online (Sandbox Code Playgroud)

还有一种替代语法:

value.shouldBeInstanceOf<Type>()
Run Code Online (Sandbox Code Playgroud)

请参阅此处了解更多信息。