mockito / mockito-kotlin

Using Mockito with Kotlin
MIT License
3.11k stars 201 forks source link

NullPointerException with boolean arguments #298

Open Atatorus opened 5 years ago

Atatorus commented 5 years ago

Hi, if I mock a method with boolean argument, I got NullPointerException. Example with this interface :

interface ITest {
    fun fun1(b: Boolean, user: User): String

    fun fun2(s: String, user: User): String
}

Here the test :

class MyTest {

    lateinit var itest: ITest
    lateinit var user: User

    @BeforeEach
    fun before() {
        itest = mock()
        user = User("Marcel", 42)
    }

    @Test
    fun fun1Test() {
        whenever(
            itest.fun1(argThat { this }, argThat { this.name == "Marcel" })
        ).thenReturn("OK")
        assertEquals("OK", itest.fun1(true, user))
    }

    @Test
    fun fun2Test() {
        whenever(
            itest.fun2(argThat { this == "abc" }, argThat { this.name == "Marcel" })
        ).thenReturn("OK")
        assertEquals("OK", itest.fun2("abc", user))
    }
}

fun2Test is ok, but test fun1Test produces NPE. I got same error with Int and Long in place of Boolean.

Is it a bug, or am I doing something wrong ?

I use version 2.0.0-RC2.

Thanks.

bohsen commented 5 years ago

Related to #307 Caused by autoboxing caveat in Mockito core. Use booleanThat, intThat, longThat etc. instead.

Atatorus commented 5 years ago

Thanks, that works ! But we have to respect order of arguments :

@Test
fun fun1bisTest() {
    whenever(
        itest.fun1(b = booleanThat { it }, user = argThat { this.name == "Marcel" })
    ).thenReturn("OK")
    assertEquals("OK", itest.fun1(true, user))
}

@Test
fun fun1terTest() {
    whenever(
        itest.fun1(user = argThat { this.name == "Marcel" }, b = booleanThat { it })
    ).thenReturn("OK")
    assertEquals("OK", itest.fun1(true, user))
}

fun1bisTest() is ok, but fun1terTest() raise a class cast exception boolean cannot be cast to user. It's a little annoying, we lost the advantage of named call argument regardless of the order. Just be careful...