Mockito's argThat returning null when in Kotlin

ぃ、小莉子 提交于 2020-07-20 08:23:30

问题


Given the following class (written in kotlin):

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

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

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)
}

The kotlin version I receive the following exception:

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

Why is it happening and how can I test that using kotlin?


回答1:


I also faced the same problem.

And finally, I found argThat() will return null, and normally the argument in the function in kotlin, does not accept null type.

So when we mock the function, it will throw IllegalStateException, because argThat returns null and argument can't be null.

My solution is to define the argument with class? so that it can accept null, but I don't know if it is a great solution



来源:https://stackoverflow.com/questions/52389727/mockitos-argthat-returning-null-when-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!