在Kotlin中构建hamcrest地图匹配器时遇到问题

时间:2018-10-30 17:41:56

标签: kotlin mockito hamcrest

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

但是当我构建匹配器时

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)

由于我无法看到正确的泛型推断,最终以null结束,并在运行时用

吹响了
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

我做错什么了吗?您可以提出解决方法吗?

1 个答案:

答案 0 :(得分:0)

如果您将火腿 k rest https://github.com/npryce/hamkrest用于Kotlin而不是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

处找到了解决方案
相关问题