Jun 27, 2013

Java unit testing with mock objects using frameworks like Mockito.

This is an extension to my blog post entitled  unit testing Spring MVC controllers for web and RESTful services with spring-test-mvc.  The purpose of this is to demonstrate the power of using mock objects via frameworks like Mockito.

This example tests a Spring MVC Controller used for servicing RESTful services, and this example illustrates a CSV file download.

public class MyAppController

    @Resource(name = "aes_cashForecastService")
    private MyAppService myAppService;

            value = "/portfolio/{portfoliocd}/detailsPositionFeed.csv",
            method = RequestMethod.GET,
            produces = "text/csv")
    public void getPositionFeedCSV(
            @PathVariable(value = "portfoliocd") String portfolioCode,
            @RequestParam(value = "valuationDate", required = true) @DateTimeFormat(pattern = "yyyyMMdd") Date valuationDate,
            HttpServletResponse response) throws Exception
            PositionFeedCriteria criteria = new PositionFeedCriteria();
            criteria.setValuationDtTm(valuationDate != null ? valuationDate
                    : new Date());
            String fileName = "test.csv"
   //headers for file download
            response.addHeader("Content-Disposition", "attachment; filename="+ fileName);
            //returns results as CSV
            String positionFeedCSV = myAppService.getPositionFeedCSV(criteria);
        catch (Exception e)
        }"Completed producing position feed CSV");
  public void setMyAppService(MyAppService myAppService)
        this.myAppService = myAppService;

Now comes the junit class using the Mockito framework to test the MyAppController.


import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

public class MyAppControllerTest
     private static final String PORTFOLIO_CODE = "abc123";
   private static final java.util.Date VALUATION_DATE = new java.util.Date();

     private MyAppService mockMyAppService;
  private MyAppController controller;

     HttpServletResponse response;
     public void setup()
        controller = new MyAppController();
        mockMyAppService = mock(MyAppServiceImpl.class);
  //The test case
     public void testGetPositionFeedCSV() throws Exception
        String str = "dummyCSV";
        //Set up behavior
        //Invoke controller
        controller.getPositionFeedCSV(PORTFOLIO_CODE, VALUATION_DATE, response);
        //Verify behavior
        verify(mockMyAppService, times(1)).getPositionFeedCSV(any(PositionFeedCriteria.class));
        verify(writer, times(1)).write(any(String.class));

The key point to note here is the ability of the mock objects to verify if a particular method was invoked and if yes, how many times was invoked. This is demonstrated with the last two lines with the verify statement. This is one of the key differences between using a mock object versus a stub. This is a common Java interview question quizzing the candidate's understanding of the difference between a mock object and stub.

Labels: , , ,


Post a Comment

Subscribe to Post Comments [Atom]

<< Home