Note that you can also use the InOrder class to verify that various methods are called in order on a single mock, not just on two or more mocks.
Suppose I have two classes Foo
and Bar
:
public class Foo {
public void first() {}
public void second() {}
}
public class Bar {
public void firstThenSecond(Foo foo) {
foo.first();
foo.second();
}
}
I can then add a test class to test that Bar
's firstThenSecond()
method actually calls first()
, then second()
, and not second()
, then first()
. See the following test code:
public class BarTest {
@Test
public void testFirstThenSecond() {
Bar bar = new Bar();
Foo mockFoo = Mockito.mock(Foo.class);
bar.firstThenSecond(mockFoo);
InOrder orderVerifier = Mockito.inOrder(mockFoo);
// These lines will PASS
orderVerifier.verify(mockFoo).first();
orderVerifier.verify(mockFoo).second();
// These lines will FAIL
// orderVerifier.verify(mockFoo).second();
// orderVerifier.verify(mockFoo).first();
}
}