Mockito的argThat在Kotlin中返回null [英] Mockito's argThat returning null when in Kotlin
问题描述
给出以下课程(用kotlin编写):
Given the following class (written in kotlin):
class Target {
fun <R> target(filter: String, mapper: (String) -> R): R = mapper(filter)
}
我能够在Java中测试代码:
I'm able to test in java, the test code:
@Test
public void testInJava() {
Target mockTarget = Mockito.mock(Target.class);
Mockito.when(mockTarget.target(
argThat(it -> true),
Mockito.argThat(it -> true)
)).thenReturn(100);
assert mockTarget.target("Hello World", it -> 1) == 100;
}
Java测试通过了预期的结果,但相同的测试用kotlin编写:
The java test pass as expected, but the same test is written in kotlin:
@Test
fun test() {
val mockTarget = Mockito.mock(Target::class.java)
Mockito.`when`(mockTarget.target(
Mockito.argThat<String> { true },
mapper = Mockito.argThat<Function1<String, Int>>({ true }))
).thenReturn(100)
assert(mockTarget.target("Hello World") { 1 } == 100)
}
kotlin版本收到以下异常:
The kotlin version I receive the following exception:
java.lang.IllegalStateException: Mockito.argThat<String> { true } must not be null
为什么会发生这种情况,如何使用Kotlin进行测试?
Why is it happening and how can I test that using kotlin?
推荐答案
截至撰写本文时,mockito-kotlin的更新时间尚未超过一年.与所有这些库一样,始终需要不断更新它们,而我也不想卡在一个未维护的库中.
As of this writing, mockito-kotlin hasn't been updated for more than a year. As with all of these libraries, there's always a constant need for keeping them up-to-date, and I didn't want to get stuck with an unmaintained library.
所以我想出了另一种方法来解决argThat
的null问题,而无需使用任何其他库.
So I came up with another way to solve the null issue with argThat
without using any other libraries.
假设我们有一个界面UuidRepository
,如下所示:
Say we've an interface UuidRepository
as follows:
interface UuidRepository {
suspend fun Entity save(entity: Entity): Entity
}
类Entity
具有两个属性,userId: String
和uuid: String
.
以下代码失败:
Mockito.verify(uuidRepository).save(argThat { it.userId == someValue && it.uuid == "test" })
出现错误:
argThat {it.userId == someValue&& it.uuid =="test"; }不能为空
argThat { it.userId == someValue && it.uuid == "test" } must not be null
要解决此问题,我们在模拟中获得所有调用,然后验证所需的调用:
To solve this, we get all the invocation on the mock and then verify the ones we want:
val invocations = Mockito.mockingDetails(uuidRepository).invocations
.filter { setOf("findById", "save").contains(it.method.name) }
.map { it.method.name to it.arguments }
.toMap()
assertThat(invocations).containsKey("save")
val first = invocations["save"]?.first()
assertThat(first).isNotNull
val entity = first as Entity
assertThat(entity.userId).isEqualTo(someValue)
assertThat(entity.uuid).isEqualTo("test")
这篇关于Mockito的argThat在Kotlin中返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!