kotlin and ArgumentCaptor – IllegalStateException

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.

Leave a Comment