Given the following class (written in kotlin):

class Target {
     fun <R> target(filter: String, mapper: (String) -> R): R = mapper(filter)
}

我可以用java进行测试,测试代码是:

@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;
}

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版本I收到以下异常:

java.lang.IllegalStateException: Mockito.argThat<String> { true } must not be null

为什么会发生这种情况?我如何使用kotlin进行测试?

推荐答案

In 2022, Mockito-Kotlin officially solves the problem.

The fix is very simple: Just import the argThat/eq/... from the mockito-kotlin package, instead of the mockito package, and everything is done!

相关:https://github.com/mockito/mockito-kotlin/wiki/Mocking-and-verifying

Kotlin相关问答推荐

如何在Jetpack Compose中的列中渲染图像

如何使用Kotlinx.LocalDateTime获取重置时间为00:00的当前日期?

用vararg替换列表的设计弃用警告

当我通过媒体通知更改音乐时不要更新我的 UI

Kotlin 复制列表中的项目以创建具有相同数据的不同对象的新列表

如何在 Kotlin 中初始化 Short 数组?

Spring Boot Kotlin 数据类未使用 REST 控制器中的默认值初始化

修改器的属性是什么,我需要更改以使角变圆且宽度更小?喷气背包组合

如何限制 Kotlin 中的枚举?

是什么让 Kotlin 中的 String 类能够使用方括号?

异常传播如何在 CoroutineScope.async 上工作?

Kotlin:如何使用第一个参数的默认值进行函数调用并为第二个参数传递一个值?

在 Kotlin 中,当枚举类实现接口时,如何解决继承的声明冲突?

@InlineOnly 注释是什么意思?

下拉通知面板时是否可以暂停Android中的任何视频(媒体播放器)应用程序?

kotlin-bom 库是做什么的?

Tornadofx - 如何在每个实例上将参数传递给 Fragment

Kotlin var lazy init

Kotlin 对象 vs 伴生对象(companion-object) vs 包作用域(package scoped)方法

函数引用和lambdas