kotlin and ArgumentCaptor - IllegalStateException

AndroidRobolectricKotlin

Android Problem Overview


I have a problem with capturing the Class argument via ArgumentCaptor. My test class looks like this:

@RunWith(RobolectricGradleTestRunner::class)
@Config(sdk = intArrayOf(21), constants = BuildConfig::class)
class MyViewModelTest {
    @Mock
    lateinit var activityHandlerMock: IActivityHandler;

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

    @Captor
    lateinit var booleanCaptor: ArgumentCaptor<Boolean>

    private var objectUnderTest: MyViewModel? = null

    @Before
    fun setUp() {
        initMocks(this)
        ...
        objectUnderTest = MyViewModel(...)
    }

    @Test
    fun thatNavigatesToAddListScreenOnAddClicked(){
        //given

        //when
        objectUnderTest?.addNewList()

        //then
        verify(activityHandlerMock).navigateTo(classCaptor.capture(), booleanCaptor.capture())
        var clazz = classCaptor.value
        assertNotNull(clazz);
        assertFalse(booleanCaptor.value);
    }
}

When I run the test, following exception is thrown:
java.lang.IllegalStateException: classCaptor.capture() must not be null
Is it possible to use argument captors in kotlin?

========= UPDATE 1:
Kotlin: 1.0.0-beta-4584
Mockito: 1.10.19
Robolectric: 3.0

========= UPDATE 2:
Stacktrace:

java.lang.IllegalStateException: classCaptor.capture() must not be null

at com.example.view.model.ShoplistsViewModelTest.thatNavigatesToAddListScreenOnAddClicked(ShoplistsViewModelTest.kt:92)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:251)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:188)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:152)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Android Solutions


Solution 1 - Android

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.

Solution 2 - Android

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"

Solution 3 - Android

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

Solution 4 - Android

As stated by CoolMind in the comment, you first need to add gradle import for Kotlin-Mockito and then shift all your imports to use this library. Your imports will now look like:

import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.isNull
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify

Then your test class will be something like this:

val mArgumentCaptor = argumentCaptor<SignUpInteractor.Callback>()

@Test
fun signUp_success() {
    val customer = Customer().apply {
    	name = "Test Name"
    	email = "[email protected]"
    	phone = "0123444456789"
    	phoneDdi = "+92"
    	phoneNumber = ""
    	countryCode = "92"
    	password = "123456"
    }
    mPresenter.signUp(customer)
    verify(mView).showProgress()
    verify(mInteractor).createAccount(any(), isNull(), mArgumentCaptor.capture())
}

Solution 5 - Android

According this solution my solution here:

fun <T> uninitialized(): T = null as T

//open verificator
val verificator = verify(activityHandlerMock)

//capture (would be same with all matchers)
classCaptor.capture()
booleanCaptor.capture()

//hack
verificator.navigateTo(uninitialized(), uninitialized())

Solution 6 - Android

Came here after the kotlin-Mockito library didn't help. I created a solution using reflection. It is a function which extracts the argument provided to the mocked-object earlier:

fun <T: Any, S> getTheArgOfUsedFunctionInMockObject(mockedObject: Any, function: (T) -> S, clsOfArgument: Class<T>): T{
    val argCaptor= ArgumentCaptor.forClass(clsOfArgument)
    val ver = verify(mockedObject)
    argCaptor.capture()
    ver.javaClass.methods.first { it.name == function.reflect()!!.name }.invoke(ver, uninitialized())
    return argCaptor.value
}
private fun <T> uninitialized(): T = null as T

Usage: (Say I have mocked my repository and tested a viewModel. After calling the viewModel's "update()" method with a MenuObject object, I want to make sure that the MenuObject actually called upon the repository's "updateMenuObject()" method:

viewModel.update(menuObjectToUpdate)
val arg = getTheArgOfUsedFunctionInMockObject(mockedRepo, mockedRepo::updateMenuObject, MenuObject::class.java)
assertEquals(menuObjectToUpdate, arg)

Solution 7 - Android

You can write a wrapper over argument captor

class CaptorWrapper<T:Any>(private val captor:ArgumentCaptor<T>, private val obj:T){
    fun capture():T{
        captor.capture()
        return obj
    }

    fun captor():ArgumentCaptor<T>{
        return captor
    }
}

Solution 8 - Android

Another approach:

/**
 * Use instead of ArgumentMatcher.argThat(matcher: ArgumentMatcher<T>)
 */
fun <T> safeArgThat(matcher: ArgumentMatcher<T>): T {
    ThreadSafeMockingProgress.mockingProgress().argumentMatcherStorage
        .reportMatcher(matcher)
    return uninitialized()
}

@Suppress("UNCHECKED_CAST")
private fun <T> uninitialized(): T = null as T

Usage:

verify(spiedElement, times(1)).method(
    safeArgThat(
        CustomMatcher()
    )
)

Solution 9 - Android

If none of the fine solutions presented worked for you, here is one more way to try. It's based on Mockito-Kotlin.

[app/build.gradle]
dependencies {
    ...
    testImplementation 'org.mockito.kotlin:mockito-kotlin:3.2.0'
}

Define Rule and Mock in your test file.

@RunWith(AndroidJUnit4::class)
class MockitoTest {
    @get:Rule
    val mockitoRule: MockitoRule = MockitoJUnit.rule()

    @Mock
    private lateinit var mockList: MutableList<String>

And here is an example.

    @Test
    fun `argument captor`() {
        mockList.add("one")
        mockList.add("two")

        argumentCaptor<String>().apply {
            // Verify that "add()" is called twice, and capture the arguments.
            verify(mockList, times(2)).add(capture())

            assertEquals(2, allValues.size)
            assertEquals("one", firstValue)
            assertEquals("two", secondValue)
        }
    }
}

Alternatively, you can also use @Captor as well.

@Captor
private lateinit var argumentCaptor: ArgumentCaptor<String>

@Test
fun `argument captor`() {
    mockList.add("one")
    mockList.add("two")

    verify(mockList, times(2)).add(capture(argumentCaptor))

    assertEquals(2, argumentCaptor.allValues.size)
    assertEquals("one", argumentCaptor.firstValue)
    assertEquals("two", argumentCaptor.secondValue)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRampsView Question on Stackoverflow
Solution 1 - AndroidIkechukwu KaluView Answer on Stackoverflow
Solution 2 - AndroidMike BuhotView Answer on Stackoverflow
Solution 3 - Androidenes.acikogluView Answer on Stackoverflow
Solution 4 - AndroidSufianView Answer on Stackoverflow
Solution 5 - AndroidneworldView Answer on Stackoverflow
Solution 6 - AndroidRe'emView Answer on Stackoverflow
Solution 7 - AndroidAmit KaushikView Answer on Stackoverflow
Solution 8 - AndroidNikolasView Answer on Stackoverflow
Solution 9 - AndroidsolamourView Answer on Stackoverflow