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:
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:

3. The syntax for an expectation looks like:
but for a verification, it looks like:

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);
although this is not recommended [1].

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

No comments:

Post a Comment