Google

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.

 
@Controller
public class MyAppController
{

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

    @RequestMapping(
            value = "/portfolio/{portfoliocd}/detailsPositionFeed.csv",
            method = RequestMethod.GET,
            produces = "text/csv")
    @ResponseBody
    public void getPositionFeedCSV(
            @PathVariable(value = "portfoliocd") String portfolioCode,
            @RequestParam(value = "valuationDate", required = true) @DateTimeFormat(pattern = "yyyyMMdd") Date valuationDate,
            HttpServletResponse response) throws Exception
    {
       
        try
        {
            
            PositionFeedCriteria criteria = new PositionFeedCriteria();
            criteria.setEntityCd(portfolioCode);
            criteria.setValuationDtTm(valuationDate != null ? valuationDate
                    : new Date());
            
            String fileName = "test.csv"
            
   //headers for file download
            response.addHeader("Content-Disposition", "attachment; filename="+ fileName);
            response.setContentType("text/csv");
            //returns results as CSV
            String positionFeedCSV = myAppService.getPositionFeedCSV(criteria);
            response.getWriter().write(positionFeedCSV);
            
        }
        catch (Exception e)
        {
           e.printStackTrace();
        }
        logger.info("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;

  @Mock
     HttpServletResponse response;
  
  @Before
     public void setup()
     {
        MockitoAnnotations.initMocks(this);
        controller = new MyAppController();
        mockMyAppService = mock(MyAppServiceImpl.class);
        controller.setMyAppService(mockMyAppService);
     }
  
  //The test case
  @Test
     public void testGetPositionFeedCSV() throws Exception
     {
        String str = "dummyCSV";
        //Set up behavior
        when(mockMyAppService.getPositionFeedCSV(any(PositionFeedCriteria.class))).thenReturn(str);
        when(response.getWriter()).thenReturn(writer);
        
        //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: , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home