kotlinmockkmockk-verify

Get number of invocations


Does MockK provide a way of finding how many times a method has been invoked on a mock object?

I'm looking for something like Mockito.mockingDetails(mock).getInvocations(), but for MockK.

I can only find a way of checking how many invocations there have been, using verify(), but not a way of getting the number of invocations.


Solution

  • You can manually store all invocations of a method. There may be an internal helper function to access the invocations.

    val invocations = mutableListOf<Invocation>()
    
    val mCar = mockk<Car>()
    
    every { 
        mCar.drive() 
    } answers {
        invocations.add(invocation)
    
        // mocked answer or call the original
        callOriginal()
    }
    
    mCar.drive()
    mCar.drive()
    
    println(invocations)