Reputation: 3415
I need to test if one objects calls other object methods in right order. Unfortunately it looks like Mockito use some kind of grouping for calls with the same parameters. I prepared example which illustrates this behavior.
public class TestInOrder {
@Test
public void test() {
Foo foo = new Foo();
Bar mockBar = mock(Bar.class);
foo.run(mockBar);
InOrder order = Mockito.inOrder(mockBar);
order.verify(mockBar).A();
order.verify(mockBar).B();
order.verify(mockBar).B();
order.verify(mockBar).A();
order.verify(mockBar).B();
}
}
class Foo {
void run(Bar mockBar) {
mockBar.A();
mockBar.B();
mockBar.B();
mockBar.A();
mockBar.B();
}
}
class Bar {
public void A() {
}
public void B() {
}
}
The result is:
org.mockito.exceptions.verification.VerificationInOrderFailure:
Verification in order failure:
bar.B();
Wanted 1 time:
-> at com.goeuro.pi.provider.busfor.TestInOrder.test(TestInOrder.java:19)
But was 3 times. Undesired invocation:
-> at com.goeuro.pi.provider.busfor.Foo.run(TestInOrder.java:32)
I don't understand why I get this error. Order of calls in test is the same as in method.
Upvotes: 3
Views: 6223
Reputation: 8641
The issue is that you expect one invocation on each mock. Instead Mockito
will count all the invocation on certain mock and will fail when 2 in a row will happen.
This is the implementation for verify method in InOrderImpl
class.
public <T> T verify(T mock) {
return this.verify(mock, VerificationModeFactory.times(1));
}
As you can see, it tells mockito
to expect exact one invocation on method.
From JavaDoc:
Allows verifying exact number of invocations.
Use VerificationMode to tell Mockito how to verify you mock. This should help:
InOrder order = Mockito.inOrder(mockBar);
order.verify(mockBar).A();
order.verify(mockBar, times(2)).B();
order.verify(mockBar).A();
order.verify(mockBar).B();
Upvotes: 3