Kotlin-test:如何测试特定类型,例如:"is y instance of X"



如何测试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}", "")
    }
}

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

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

还有另一种语法:

value.shouldBeInstanceOf<Type>()

有关更多信息,请参阅此处。

从 Kotlin 1.5 开始,Kotlin 测试中包含一个很好的解决方案:

assertIs<TypeExpected>(value)

这不仅会断言valueTypeExpected类型,它还会智能转换value,以便您可以访问所有TypeExpected方法。只需包含依赖项,例如:

testImplementation("org.jetbrains.kotlin:kotlin-test-junit5:1.7.10")

你可以做这样的事情

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
class AssertIsTests {
    @Test
    fun `test for list`() {
        val list = Collector.List.collect(1, 1, 2, 2, 3)
        assertEquals(5, list.size)
        // assertEquals(1, list[0])  won't compile: list is of type Collection<Int> which doesn't support []
        assertIs<List<Int>>(list)         // from now on list is of type List<Int>!
        assertEquals(4, list.indexOf(3))  // now there are all list methods
        assertEquals(1, list[0])          // including indexed getters
    }
    @Test
    fun `test for set`() {
        val set = Collector.Set.collect(1, 1, 2, 2, 3)
        assertEquals(3, set.size)  // Set with duplicates removed
        assertIs<Set<Int>>(set)    // from now on set is of Type Set<Int>
    }
}
enum class Collector {
    List {
        override fun collect(vararg args: Int) = args.toList()
    },
    Set {
        override fun collect(vararg args: Int) = args.toSet()
    };
    abstract fun collect(vararg args: Int): Collection<Int>
}

2020 年,Kotlintest 库更名为 Kotest,软件包名称也相应更改。所以我决定发布@TheOperator答案的更新版本。

要检查valueType 的实例还是子类型,请执行以下操作:

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

另一种方法是核心匹配器的方法:

import io.kotest.matchers.types.shouldBeInstanceOf
val castedValue: Type = value.shouldBeInstanceOf<Type>()

请注意,在这种情况下,将返回强制转换为指定类型的值,该值可用于进一步的验证。

<小时 />

如果需要精确类型匹配,请使用另一组方法:

import io.kotest.matchers.should
import io.kotest.matchers.types.beOfType
import io.kotest.matchers.types.shouldBeTypeOf
value should beOfType<Type>()
val castedValue: Type = value.shouldBeTypeOf<Type>()

相关内容

最新更新