Using Mockito to Unit Test Java Applications

Steve Neal Development, Java Programming, Tool support 23 Comments

If you’ve spent any time writing unit tests then you’ll know that it’s not always straight-forward. Certain things are inherently hard to test. In this post I’ll show you the basic principles of creating mock objects with a little help from the Mockito mocking tool.

One common problem faced when unit testing is how to test one object when it is dependant on another object. You could create instances of both the object under test and the dependent object and test them both together, however testing aggregated objects is not what unit testing is about – unit tests should test individual objects for their correct behaviour, not aggregations of objects! Moreover, this approach just won’t work if the dependent object hasn’t even been implemented yet.

A common technique for handling dependencies in unit tests is to provide a surrogate, or “mock” object, for the dependent object instead of a real one. The mock object will implement a simplified version of the real objects methods that return predictable results and can be used for testing purposes.

The drawback of this approach is that in a complex application, you could find yourself creating a lot of mock objects. This is where frameworks like Mockito can save you a lot of time and effort.

A Test Scenario

To demonstrate what you can do with Mockito, we’ll examine how we might test an Account object that is dependant on a data access object (AccountDAO).  The account object can calculate the charges applicable in the current month by using the DAO to count the number of days overdrawn and then performing a simple calculation on the value obtained from that call. The method names on the classes we’ll use are self-explanatory:

AccountAndDAO
To test this thoroughly, we should test two things:

  1. that the account obtains the number of overdrawn days by calling the correct method on the DAO,
  2. that the account calculates the correct fees based upon the value it gets back from the call.

Testing that the account calls the correct method on the DAO

Using JUnit to run the test case, we could write something like this:

import static org.mockito.Mockito.*;

public class TestAccount {
    @Test
    public void checkAccountCallsDaoMethods() {
        //create the object under test
        Account account = new Account();

        //create a mock DAO
        AccountDAO mockedDao = mock(AccountDAO.class);	

        //associate the mocked DAO with the object under test
        account.setDAO(mockedDao);

        //call the method under test
        long charge = account.calculateCharges();

        //verify that the 'countOverdrawnDaysThisMonth' was called
        verify(mockedDao).countOverdrawnDaysThisMonth();
    }
}

Taking centre stage in all this is the Mockito class which has a bunch of static methods that are used within the unit test (note the static import on line 1).

The call to the ‘mock’ method (line 10) creates a mock object that can be used in place of a real AccountDAO. The call to ‘verify’ (line 19), will throw an exception if the ‘countOverdrawnDaysThisMonth’ method was not called on the mock object.

It is worth noting here that this is a simple example which just demonstrates the basic principle of verification, it is also possible to use the verify method to check for parameter values and ranges in the method call too.

Testing that the account performs its calculations correctly

In the above example, we mocked the DAO but didn’t specify what any of the mocked methods should do. In this case, all methods will return sensible default values of: null, zero or false. More commonly we need to specify something other than these defaults when writing our tests:

import static org.mockito.Mockito.*; 
import static junit.framework.Assert.*;
import org.junit.*;

public class TestAccount {
    private Account account;

    @Before
    public void setup() {
        AccountDAO mockedDao = mock(AccountDAO.class);

    	//specify that this method on the mock object should return 8
        when(mockedDao.countOverdrawnDaysThisMonth()).thenReturn(8);

        account = new Account();
        account.setDAO(mockedDao);
    }

    @Test
    public void checkChargesWhenOverdrawn() {
        //call the method under test
        long charge = account.calculateCharges();

        //assert that the charge was £2 per day overdrawn
        assertEquals(charge, 16);
    }
}

The statement on line 13 specifies that whenever the ‘countOverdrawnDaysThisMonth’ is called it should return a value of 8; overriding the default of zero.

Given that the correct charge is two pounds (or dollars) per day overdrawn, then the assertion on line 25 will pass if the account performed the correct calculation (8 x 2 = 16 right).

Comments

There’s loads more to Mockito than we’ve looked at here. It’s a neat testing tool that works great with JUnit or TestNG. I’ve found that it’s small enough to learn quickly and capable enough to be really useful. Give it a go and write a comment below to let me know what you think of it.

Comments 23

  1. camilo lopes

    i have a one suggestion to this post: why did not you publish the code from Account and AccountDAO? i believe that to beginner, it will be too good, like this we can see all structure.

    thaks :D

  2. camilo lopes

    i have tested the code above, and it is not working very well, your explanation was good, but i had to adapt some codes to it works correctly, see:
    AccountDao mockeddao = Mockito.mock(AccountDao.class);
    Mockito.when(AccountDao.countOverDays()).thenReturn((long) 8);

  3. Steve Neal

    Well spotted Camilo! Thanks for noticing that. Yes the DAO in the UML returns a long, so you’ll need to pass a long into the test. You could have put .thenReturn(8L) too, which is a bit nicer than casting an int.

  4. Sum

    I went over a few mockito articles online (including mockito.org) but could not really understand exactly how it works. This article has made it clear to me. Thanks a bunch for writing it!

  5. Ezio

    Thanks for the informative post on Mockito. If you are willing to discuss more on unit testing with mockit and unit testing for other languages can check out Mockito Mock forum which is exclusively for unit testing for
    different languages. It is a upcoming forum and needs support to make it strong so we can have forum where people can share their knowledge on
    Testing.

  6. Steve Neal

    Well spotted Tim, it took two years for someone to spot that – thanks. I’ve updated the post with your correction.


    Tim:

    surely this line:

    account.setDAO(dao);

    in both tests should read

    account.setDAO(mockedDao);

    ?

  7. Keith B

    A little typo, the under the second code snippet:

    ‘The statement on line 18 specifies that whenever the ‘countOverdrawnDaysThisMonth’ is called it should return a value of 8; overriding the default of zero.’

    Line 18 is blank. The actual call is on line 13. Great example!

  8. Steve Neal

    Thanks Keith. Well spotted :)


    Keith B:

    A little typo, the under the second code snippet:

    ‘The statement on line 18 specifies that whenever the ‘countOverdrawnDaysThisMonth’ is called it should return a value of 8; overriding the default of zero.’

    Line 18 is blank. The actual call is on line 13. Great example!

  9. venkateswarareddy

    Hi,
    Simple and easy to understnad.In my project we are using mockito,i need code of account and accountdao classes also
    can u plz send me

  10. Jesus Macias

    I have a another suggestion to this post: why did not you publish the code from Account and AccountDAO? I believe that for beginner will be very good, like this we can see all structure.

    Thanks a lot

    1. Steve Neal

      Hi, I don’t have the code from this post any more but if you copy and past the code from above, you should be pretty close to a working example. Thanks for taking the time to read it.

  11. Phil B

    To all those requesting the code, with test driven development you write the test before coding. The test fails and forces you to write code to make it pass. With an IDE like Eclipse, it will even offer you the templates for the classes and methods you need. So all you have to do is paste the test into your IDE and write whatever code you like to make it pass. Then you will understand it!

Leave a Reply

Your email address will not be published. Required fields are marked *