Because I have been using EasyMock for the last 5 years, I'm having trouble kicking the habit. So, here is a list of the more common things I want Mockito to do but keep forgetting how.
1. Using any argument
Use Mockito.anyXXX methods. Here is an example that expects any String:
Mockito.when(Note that if we mix wildcards with fixed values, we need to use Mockito.eq(...) on the fixed value. For example:
mock.takeArgument(Mockito.anyString())
).thenReturn(toReturn);
Mockito.when(mock.takeArguments(Mockito.anyString(), Mockito.eq(2))).thenReturn("returned");
2. Throwing an Exception in a method that does not return anything:
Mockito.doThrow(x).when(mock).callMethodWhoseReturnTypeIsVoid();
3. The syntax for an expectation looks like:
Mockito.when(mock.getText()).thenReturn("test")but for a verification, it looks like:
Mockito.verify(mock).callMethodWhoseReturnTypeIsVoid();
4. You can decorate collaborating objects and verify they were called. For example:
ClassToBeMocked real = new ClassToBeMocked();although this is not recommended [1].
ClassToBeMocked spy = Mockito.spy(real);
toTest = new ClassForTesting(spy);
toTest.hitMocksVoidMethod();
Mockito.verify(spy).callMethodWhoseReturnTypeIsVoid();
[1] Mockito JavaDocs section 13 on "Spying on Real Objects".
No comments:
Post a Comment