kotlin and ArgumentCaptor - IllegalStateException

耗尽温柔 提交于 2019-12-03 04:16:19
Mike Buhot

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.

For some, there is a file, MockitoKotlinHelpers.kt provided by Google in the Android Architecture repo. It provides a convenient way to call capture.. just 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.

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)

        }
neworld

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

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 = "test@example.com"
        phone = "0123444456789"
        phoneDdi = "+92"
        phoneNumber = ""
        countryCode = "92"
        password = "123456"
    }
    mPresenter.signUp(customer)
    verify(mView).showProgress()
    verify(mInteractor).createAccount(any(), isNull(), mArgumentCaptor.capture())
}

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)

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