9

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

在 Kotlin 测试中我是否缺少某些东西,例如:

value shouldBe instanceOf<ExpectedType>()

以下是我的实现方式:

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

    }
}
4

1 回答 1

22

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

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

value should beInstanceOf<Type>()

还有一种替代语法:

value.shouldBeInstanceOf<Type>()

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

于 2019-04-29T12:01:22.160 回答