Mockito in a nutshell

What is it
As the name implies – it’s a mock framework.
ie. allows for the creation of mock objects, to be used in place of “real” objects (often external dependencies such as databases, JMS servers..) when unit testing.

What’s good about it
The main features are listed on the Mockito website.
Two features stand out:
– ability to mock classes as well as interfaces
– lean API which makes for a  shorter learning curve and more readable code when compared with existing mock frameworks such as easyMock, JMockit…

How does it work

Class under Test:

Class BusinessLogic  {

   Public void execute (ExternalSystem externalSystem) {

     //retrieve a value from an external system:
     //could be slow, unreliable
     String value = externalSystem.fetch();


class BusinessLogicTest {

   public void testExecute(){
      //Initialise mock system
      ExternalSystem mockSystem = mock (ExternalSystem.class)

      //make sure the fetch method of the mocked ExternalSystem will return "ABC"
      //(only needed if that value is critical to the test)

      //exercise the class under test
      //will call the mocked system initialized above
      new BusinessLogic().execute();

      //check mock system has been called once
      verify (mockSystem, times(1)).fetch()

One thought on “Mockito in a nutshell

  1. Pingback: Recent Links Tagged With "businesslogic" - JabberTags

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s