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?
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.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With