kotlin and ArgumentCaptor - IllegalStateException

The return value of classCaptor.capture() is null, but the signature of IActivityHandler#navigateTo(Class, Boolean) does not allow a null argument.

The mockito-kotlin library provides supporting functions to solve this problem.

Code should be:

    @Captor
    lateinit var classCaptor: ArgumentCaptor<Class<BaseActivity>>

    @Captor
    lateinit var booleanCaptor: ArgumentCaptor<Boolean>

    ...

    @Test
    fun thatNavigatesToAddListScreenOnAddClicked(){
        //given

        //when
        objectUnderTest?.addNewList()

        //then
        verify(activityHandlerMock).navigateTo(
com.nhaarman.mockitokotlin2.capture<Class<BaseActivity>>(classCaptor.capture()), 
com.nhaarman.mockitokotlin2.capture<Boolean>(booleanCaptor.capture())
)
        var clazzValue = classCaptor.value
        assertNotNull(clazzValue);
        val booleanValue = booleanCaptor.value
        assertFalse(booleanValue);
    }

OR

var classCaptor = com.nhaarman.mockitokotlin2.argumentCaptor<Class<BaseActivity>>()
var booleanCaptor = com.nhaarman.mockitokotlin2.argumentCaptor<Boolean>()
...
 verify(activityHandlerMock).navigateTo(
classCaptor.capture(), 
booleanCaptor.capture()
)

also in build.gradle add this:

testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"

Use kotlin-mockito https://mvnrepository.com/artifact/com.nhaarman/mockito-kotlin/1.5.0 as dependency and sample code as written below :

argumentCaptor<Hotel>().apply {
    verify(hotelSaveService).save(capture())

    assertThat(allValues.size).isEqualTo(1)
    assertThat(firstValue.name).isEqualTo("İstanbul Hotel")
    assertThat(firstValue.totalRoomCount).isEqualTo(10000L)
    assertThat(firstValue.freeRoomCount).isEqualTo(5000L)
}

From this blog

"Getting matchers to work with Kotlin can be a problem. If you have a method written in kotlin that does not take a nullable parameter then we cannot match with it using Mockito.any(). This is because it can return void and this is not assignable to a non-nullable parameter. If the method being matched is written in Java then I think that it will work as all Java objects are implicitly nullable."

A wrapper function is needed that returns ArgumentCaptor.capture() as nullable type.

Add the following as a helper method to your test

fun <T> capture(argumentCaptor: ArgumentCaptor<T>): T = argumentCaptor.capture()

Please see, MockitoKotlinHelpers.kt provided by Google in the Android Architecture repo for reference. the capture function provides a convenient way to call ArgumentCaptor.capture(). Call

verify(activityHandlerMock).navigateTo(capture(classCaptor), capture(booleanCaptor))

Update: If the above solution does not work for you, please check Roberto Leinardi's solution in the comments below.