Tuesday, March 6, 2012

Mockito crib sheet

I've been using EasyMock for years. It's very nice but looks somewhat dated when compared to Mockito.

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(
mock.takeArgument(Mockito.anyString())
).thenReturn(toReturn);
Note that if we mix wildcards with fixed values, we need to use Mockito.eq(...) on the fixed value. For example:
       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();
ClassToBeMocked spy = Mockito.spy(real);
toTest = new ClassForTesting(spy);
toTest.hitMocksVoidMethod();
Mockito.verify(spy).callMethodWhoseReturnTypeIsVoid();
although this is not recommended [1].


[1] Mockito JavaDocs section 13 on "Spying on Real Objects".

No comments:

Post a Comment