【问题标题】:Problem building a hamcrest map matcher in Kotlin在 Kotlin 中构建 hamcrest 地图匹配器的问题
【发布时间】:2018-10-30 17:41:55
【问题描述】:

我正在开发一个简单的模拟,它在使用具有给定条目的集合调用函数时返回一个值。

但是当我构建匹配器时

import org.mockito.hamcrest.MockitoHamcrest.argThat
import org.hamcrest.collection.IsMapContaining.hasEntry

val matcher : Matcher<Map<String, String>> = hasEntry("key", "value")  as Matcher<Map<String, String>>
val args : Map<String, String> = argThat(matcher)

它最终为空,因为据我所见并没有正确推断泛型,并且在运行时使用

java.lang.IllegalStateException: argThat(matcher) must not be null

最终我只想设置如下模拟:

doReturn(returnValue).`when`(referenceObj).functionName(args)

我的依赖包括:

  • mockito-core 2.16.0
  • hamcrest-all 1.3
  • kotlin-reflect 1.2.30
  • kotlin-stdlib 1.2.30
  • kotlin-stdlib-jdk7 1.2.30
  • kotlin-stdlib-jdk8 1.2.30

我做错了吗?你能推荐一个解决方法吗?

【问题讨论】:

  • 最后我刚刚使用了逐字 arg 匹配器,它适用于非常小的地图:doReturn(returnValue).when(referenceObj).apply(mapOf(...))

标签: kotlin mockito hamcrest


【解决方案1】:

如果你对 Kotlin 使用 hamkrest https://github.com/npryce/hamkrest 而不是 hamcrest,你可以尝试创建:

fun <K, V> hasEntry(key: K, value: V): Matcher<Map<K, V>> {
    return has("entry $key -> $value", { it[key] }, equalTo(value))
}

然后在你的测试中:

val map = mapOf("some-key" to "some-value")

assertThat(map, hasEntry("some-key", "some-value"))

我在这里找到了解决方案https://github.com/araqnid/app-status/blob/master/src/test/kotlin/org/araqnid/appstatus/Matchers.kt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多