kotlin and ArgumentCaptor - IllegalStateException

后端 未结 8 1287
长发绾君心
长发绾君心 2020-12-30 18:44

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

@RunWith(RobolectricGradleTestRunner::class)
@Config(sd         


        
相关标签:
8条回答
  • 2020-12-30 19:13

    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())
    
    0 讨论(0)
  • 2020-12-30 19:20

    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)
    
    0 讨论(0)
提交回复
热议问题