Alex Collins is a enterprise Java developer and currently works in the UK. He has worked in the insurance, publishing, telecoms and supply chain. In his spare time he codes in Python, Clojure and Scala (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. You can read more from them at their website. View Full User Profile

5 minute Mockito

09.10.2010
| 62229 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!

Lance Kind replied on Sun, 2014/01/05 - 5:24pm in response to: Robert Bowen

JBehave is a framework for BDD, Behavior Driven Development.  Using JBehave you can confirm if your feature works as the customer expects it, so the testing level is really closer to black box testing. It's an implementation of system testing where all or much of the software system is being tested by one test.

Mockito is for unit testing which is for testing if a specific unit of code (a class) works as designed.  Unit tests are white box tests and are written by the same person that designed and wrote the unit of code.

Unit testing and BDD are two different levels of testing and both are important as they compliment each other.  Unit tests execute and return results in minutes where system tests such as BDD take hours to days to return results.  Mocking tools such as mockito allow you to DISABLE something you don't want to test which is certainly valuable for unit testing so you don't need the whole system operational just to test one unit of code.  You *could* use mockito for mocking when writing BDD tests but it's a bit unusual (but not unheard of) to chose to NOT test something when confirming if the system works as the customer expects.

Unit testing helps engineering confirm that their design and units of code operate as the developers expected it to. BDD and system testing confirm that the sum of the whole system operates as the requirements (or customer) intended.  Because unit tests operate so fast and give good direction where in the design a problem lies, an engineering team can detect and fix regressions in minutes to hours what normally takes days to weeks.  System tests such as BDD tests tell the organization what features are complete and at any given day, what features are not.  This allows them to make ship/no-ship decisions. Additionally, automated BDD tests create real time documentation of the actual set of features the application has.

I hope that helps!

Lance Kind

Agile Development and Process Coach

206 866 5983

Comment viewing options

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