Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Mockito TooManyActualInvocations

I am writing a testing code using the Mockito. I faced the TooManyActualInvocations error.

org.mockito.exceptions.verification.TooManyActualInvocations: 
mockView.enableProgressBar(0);
Wanted 1 time:
-> at com.MyPresenterTest.doSomething(MyPresenterTest.kt:160)
But was 2 times. Undesired invocation:
-> at com.MyPresenter.doSomething(MyPresenter.kt:195)

Here is my sample code:

class MyPresenter(val view: MyView) {

    fun doSomething() {
        view.enableProgressBar(0)
        view.enableProgressBar(1)
        view.enableProgressBar(2)
        view.enableProgressBar(0)
    }

}

And here is my testing code:

@Test
fun doSomethingTest() {
    myPresenter.doSomething()

    Mockito.verify(mockView).enableProgressBar(0)
    Mockito.verify(mockView).enableProgressBar(1)
    Mockito.verify(mockView).enableProgressBar(2)
    Mockito.verify(mockView).enableProgressBar(0)
}

If I remove this line or change the value from '0' to other value which is not duplicated, it works fine.

How can I fix this?

like image 385
yoonhok Avatar asked Nov 29 '18 06:11

yoonhok


2 Answers

TooManyActualInvocations means... too many actual invocations.

This has to work fine:

@Test
fun doSomethingTest() {
    myPresenter.doSomething()
    Mockito.verify(mockView, times(2)).enableProgressBar(0)
    Mockito.verify(mockView).enableProgressBar(1)
    Mockito.verify(mockView).enableProgressBar(2)
}

As enableProgressBar was called twice with 0 argument, then the assertion should be appropriate (should assert that it was called twice). Or you can use some convenient Mockito methods such as atLeastOnce(), atMost(2), etc. instead of straightforward times if you want to leave some space for implementation specifics.

like image 104
nyarian Avatar answered Nov 14 '22 23:11

nyarian


I found the resolution.

I didn't know about the "InOrder" interface. Below code resolve my issue.

@Test
fun doSomethingTest() {
    myPresenter.doSomething()

    val inOrder = Mockito.inOrder(mockView)

    inOrder.verify(mockView).enableProgressBar(0)
    inOrder.verify(mockView).enableProgressBar(1)
    inOrder.verify(mockView).enableProgressBar(2)
    inOrder.verify(mockView).enableProgressBar(0)
}
like image 45
yoonhok Avatar answered Nov 15 '22 00:11

yoonhok