Alex Collins is a enterprise Java developer and currently works in the UK for one of the largest insurance and breakdown providers. In his spare time he codes in Python and Haskell (but not at the same time) and enjoys a multitude of sports. His catchphrase is K.I.S.S! Alex has posted 20 posts at DZone. View Full User Profile

5 minute Mockito

09.10.2010
| 39483 views |
  • submit to reddit

Some might find EasyMock a little frustrating and perhaps even too convoluted - here's a look at Mockito, a similar framework but with less complex use leading to quicker and simpler mock testing.

What is Mockito?

Apart from having a catchy name, Mockito attempts to think about mocking in a different way. Stated as an easy and lightweight alternative to EasyMock, Mockito is what you might call a Test Spy, and it seems to live up to all three of those ideologies. From its feature list, you can see it has a K.I.S.S approach (which I always like);

 Some other features:

  • Mocks concrete classes as well as interfaces
  • Little annotation syntax sugar - @Mock
  • Verification errors are clean - click on stack trace to see failed verification in test; click on exception's cause to navigate to actual interaction in code. Stack trace is always clean.
  • Allows flexible verification in order (e.g: verify in order what you want, not every single interaction)
  • Supports exact-number-of-times and at-least-once verification
  • Flexible verification or stubbing using argument matchers (anyObject(), anyString() or refEq() for reflection-based equality matching)
  • Allows creating custom argument matchers or using existing hamcrest matchers

One of my pet hates about EasyMock is its rather convoluted stacktraces when your mocks have failed or have been setup incorrectly. With Mockito, you are supposed to be able to get what you need from a failure - answers! Of course, there's only so much a framework can do; your tests need to be written properly in the first place, but we all do that, don't we?! 

A scenario

To demonstrate Mockito in a real-world example, we'll be mocking one interface. Below is DocumentRepository, whose FileBaseDocumentRepository implementation depends on a FileService instance (injected and the subject of our mock):

// package & import removed for brevity
public interface DocumentRepository {

    void addDocument(Document doc);

    Document getDocument(DocumentID docId);
}

And here's FileService, the class we'll be mocking (haha!) in our example:

// again, no packages or imports for brevity
public interface FileService {
    File createFile(String name);

    File getFile(String name);

    boolean fileExists(String filename);

    boolean fileExists(File file);
}

Brewing Mockito

In our FileBasedDocumentRepository implementation of DocumentRepository, we use the FileService to check if a file exists - via the fileExists(File f) method - and to get a file if so - via the getFile(File f) method. So, we need Mockito to do it's thing, and as you might expect we'd need to create our mocked instance by doing the following:

FileService fileService = mock(FileService.class);

Pretty easy stuff so far.

Next we'll need to tell the framework what to do when our two calls to FileService - fileExists and getFile - are made. To do so we use the when method:

when(fileService.fileExists(anyObject()));

Now we'll use our DocumentRepository and make an assertion using standard JUnit:

assertNull("Doc with non-existent name doesn't exist", docRepo.getDocument(doc.getID()));

 and finally we verify our mock calls:

verify(fileService);

So there you have it - a simple 5 minute introduction to Mockito. I recommend you read the Mockito wiki as it has a comparison of EasyMock amongst plenty of other things. Also, head on over to its feature list and FAQ pages or just download it.

Published at DZone with permission of its author, Alex Collins.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Robert Bowen replied on Mon, 2010/09/13 - 4:26am

Cool library. Care to comment on whether you think Mockito is better or even comparable to JBehave?

>Apart from having a catchy name ...

 It's catchy enough but here in the Spanish-speaking world it gives us all a chuckle because a 'moquito' (which is pronounced the same as 'mockito' more or less) is a little booger.

 

fyi

Bob

 

Alex Collins replied on Mon, 2010/09/13 - 1:46pm in response to: Robert Bowen

haha, thanks for the info Bob. I'm actually learning Spanish so I'll keep that one for future fun ;)

I can't really comment on JBehave as I've never used it, but thanks for posting as it'll be my next investigative target for mocking. I may even wright a post on it.

Thanks for reading!

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.