Here is a simple example:
//given MyQueue mock = mock(MyQueue.class); given(mock.isEmpty()).willReturn(false, true); given(mock.nextItem()).willReturn(someItem); //when mock.isEmpty(); //yields false mock.nextItem(); //yields someItem mock.isEmpty(); //yields true //then InOrder inOrder = inOrder(mock); inOrder.verify(mock).isEmpty(); inOrder.verify(mock).nextItem(); inOrder.verify(mock).isEmpty();
willReturn(false, true) means: return false on the first call and true on the second. The InOrder object InOrder used to check the order of the call. nextItem() or remove the nextItem() call and the test will fail.
Alternatively, you can use this syntax:
given(mock.isEmpty()). willReturn(false). willReturn(true). willThrow(SpecialException.class);
If you need even more powerful mocking semantics, you can introduce heavy artillery - a response to the answer:
given(mock.isEmpty()).willAnswer(new Answer<Boolean>() { private int counter = 0; @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { switch(++counter) { case 1: return false; case 2: return true; default: throw new SpecialException(); } } });
But this can easily lead to an unreachable test code, use it with caution.
Finally, you can peek into your real object by ridiculing only the selected methods.
Tomasz Nurkiewicz
source share