Edgblog

November 10, 2008

Mockito in a nutshell

Filed under: java — edgblog @ 7:26 pm

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();
   }
 }

Unit-Test

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)
      stub(mockSystem.fetch()).toReturn("ABC");

      //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()
    }
}

1 Comment »

  1. [...] public links >> businesslogic Mockito in a nutshell Saved by zekdempel on Wed 29-10-2008 The Science of Reports (contd.) Saved by suavenyc72 on Mon [...]

    Pingback by Recent Links Tagged With "businesslogic" - JabberTags — October 30, 2008 @ 9:04 am | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Connecting to %s

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.