kotlin and ArgumentCaptor - IllegalStateException

后端 未结 8 1322
长发绾君心
长发绾君心 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: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  getTheArgOfUsedFunctionInMockObject(mockedObject: Any, function: (T) -> S, clsOfArgument: Class): 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  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)
    

提交回复
热议问题