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: , , ,

Jun 17, 2013

JUnit with Mockito tutorial

Unit testing is very important in development life cycle, and you can expect questions regarding mock objects and unit testing in general. This post extends the blog post relating to writing a mapper class for Apache Camel. This post writes a JUnit test with Mockito for the PersonMapper class.


Step 1: Have the relevant dependencies required to write unit tests.

 
<dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.10</version>
 <scope>test</scope>
</dependency>
<dependency>
 <groupId>org.mockito</groupId>
 <artifactId>mockito-core</artifactId>
 <version>1.8.5</version>
 <scope>test</scope>
</dependency>


Step 2: The class that is being unit tested. The PersonMapper.java



 
package com.mycompany.app5;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.camel.Exchange;
import org.springframework.stereotype.Component;

@Component("personMapper")
public class PersonMapper
{
    
    private static final String HEADER_STATUS = "status";
    private static final String HEADER_DEST_FILE_SUFFIX = "dest_file_suffix";
    
    enum Status
    {
        accepted, rejected
    };
    
    public Object service(List<List<String>> data, Exchange exchange)
    {
        List<Map<String, String>> results = new ArrayList<Map<String, String>>();
        
        Map<String, String> headerLine = new LinkedHashMap<String, String>();
        headerLine.put("surname", "surname");
        headerLine.put("firstname", "firstname");
        headerLine.put("age", "age");
        
        results.add(headerLine);
        
        boolean accepted = true;
        
        for (List<String> line : data)
        {
            Map<String, String> resultLine = new LinkedHashMap<String, String>();
            resultLine.put("surname", line.get(1));
            resultLine.put("firstname", line.get(0));
            resultLine.put("age", line.get(2));
            results.add(resultLine);
            
            if (line.get(1) == null || line.get(2) == null)
            {
                accepted = false;
            }
            
        }
        
        if (accepted)
        {
            exchange.getIn().setHeader(HEADER_STATUS, Status.accepted.name());
        }
        else
        {
            exchange.getIn().setHeader(HEADER_STATUS, Status.rejected.name());
        }
        
        String srcFileName = (String) exchange.getIn().getHeader("CamelFileNameOnly");
        exchange.getIn().setHeader(HEADER_DEST_FILE_SUFFIX, srcFileName);
        
        return results;
        
    }
}


Step 3: The unit test itself with mock objects. The Exchange and Message objects from Apache Camel are mocked using the Mockito framework. Here is the PersonMapperTest class.

 
package com.mycompany.app5;

import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

import junit.framework.Assert;

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;

public class PersonMapperTest
{
    
    @Mock
    Exchange mockExchange;
    
    @Mock
    Message mockMessage;
    
    PersonMapper personMapper;
    
    @Before
    public void setup()
    {
        mockExchange = mock(Exchange.class);
        mockMessage = mock(Message.class);
        personMapper = new PersonMapper();
        
        when(mockExchange.getIn()).thenReturn(mockMessage);
        //invoking a void method
        doNothing().when(mockMessage).setHeader(Mockito.anyString(), Mockito.anyString());
        //mock return values
        when(mockMessage.getHeader("CamelFileNameOnly")).thenReturn("capitalexpenses_20130510.csv");
        
    }
    
    @Test
    public void testService()
    {
        @SuppressWarnings("unchecked")
        List<LinkedHashMap<String, String>> result = (List<LinkedHashMap<String, String>>) personMapper.service(
                getPersonRecords(), mockExchange);
        
        Assert.assertNotNull(result);
        Assert.assertEquals(2, result.size());
        LinkedHashMap<String, String> headerRec = result.get(0);
        LinkedHashMap<String, String> record = result.get(1);
        String headerStr = headerRec.values().toString();
        String recordStr = record.values().toString();
        
        Assert.assertEquals(
                "[surname, firstname, age]",
                headerStr
                );
        
        Assert.assertEquals(
                "[Smith, John, 35]",
                recordStr
                );
    }
    
    private List<List<String>> getPersonRecords()
    {
        List<List<String>> values = new ArrayList<List<String>>(5);
        
        List<String> asList = Arrays.asList(new String[]
        {
            "John", "Smith", "35"
        });
        values.add(asList);
        return values;
    }
}

Labels: , ,

Dec 13, 2012

Unit testing Spring MVC controllers for web and RESTful services with spring-test-mvc

As Web application and RESTful web services are very common in enterprise applications, it is imperative to unit test the controllers. There are a number of strategies to unit test your controllers in an MVC framework. For example, running an embedded web server like jetty, and then run the unit tests against the web server, etc. The spring-test-mvc project makes testing your Spring MVC controllers very easy without starting an embedded server. This blog post will take you through the key steps involved.


Step 1: You need to have the right third-party libraries. The key ones to take note are spring-test-mvc, spring-test, json-path, hamcrest-library, hamcrest-core, and mockito-core.

 
        <dependency>
   <groupId>org.mockito</groupId>
   <artifactId>mockito-core</artifactId>
   <scope>test</scope>
   <exclusions>
    <exclusion>
     <groupId>org.hamcrest</groupId>
     <artifactId>hamcrest-core</artifactId>
    </exclusion>
   </exclusions>
  </dependency>
  
  <dependency>
   <groupId>org.hamcrest</groupId>
   <artifactId>hamcrest-library</artifactId>
   <version>1.3</version>
  </dependency>
  
  <dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-mapper-asl</artifactId>
   <version>1.9.8</version>
   <scope>runtime</scope>
  </dependency>

  <dependency>
   <groupId>javax.xml.bind</groupId>
   <artifactId>jaxb-api</artifactId>
   <version>2.2.6</version>
   <scope>runtime</scope>
  </dependency>

  <!-- JSON XPATH library -->
  <dependency>
   <groupId>com.jayway.jsonpath</groupId>
   <artifactId>json-path</artifactId>
   <version>0.5.6</version>
  </dependency>
  
  <!-- spring -->
  
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>org.springframework.context</artifactId>
   <version>3.1.0.RELEASE</version>
   <exclusions>
    <!-- Exclude Commons Logging in favour of SLF4j -->
    <exclusion>
     <groupId>org.apache.commons</groupId>
     <artifactId>com.springsource.org.apache.commons.logging</artifactId>
    </exclusion>
   </exclusions>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-aop</artifactId>
   <version>3.1.0.RELEASE</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-aspects</artifactId>
   <version>3.1.0.RELEASE</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-beans</artifactId>
   <version>3.1.0.RELEASE</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>3.1.0.RELEASE</version>
   <exclusions>
    <exclusion>
     <artifactId>commons-logging</artifactId>
     <groupId>commons-logging</groupId>
    </exclusion>
   </exclusions>
  </dependency>
  
  <!-- for tspring testing -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-test</artifactId>
   <version>3.1.0.RELEASE</version>
  </dependency>
  
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-test-mvc</artifactId>
   <version>1.0.0.M1</version>
  </dependency>

  
  

Step 2: The next step is to define a Spring MVC controller that we will be writing unit test for.

 
package com.myapp.accounting.aes.securities.pricehistory.controller;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.security.authentication.LockedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.myapp.accounting.securities.pricehistory.model.PriceHistory;
import com.myapp.accounting.securities.pricehistory.service.PriceHistoryService;
import com.myapp.accounting.dm.model.refdata.securities.MarketDataSecurityPriceHist;
 

 @Controller
public class PriceHistoryController {
 
    /**
     * Service for accessing the Market Data repository. Contains the business logic.
     */
    @Resource(name = "aes_priceHistoryService")
    private PriceHistoryService securityPriceService;


 @RequestMapping(value = "/pricehistory", 
                 method = RequestMethod.GET)
 @ResponseBody
 public List<MarketDataSecurityPriceHist> getPriceHistory(@RequestParam(value="latestUpdatedTimeStamp", required=true) @DateTimeFormat(pattern="dd MMM yyyy HH:mm:ss") Date latestUpdatedTimeStamp,
                                                     @RequestParam(value="maxRecords", required=false, defaultValue="100") int maxRecords) throws Exception 
 {  
     // call the business service
     PriceHistory result = securityPriceService.getPriceHistory(maxRecords, latestUpdatedTimeStamp);
      
     return result.getHistory();
 }
}


Step 3: The PriceHistory object that holds a list of "MarketDataSecurityPriceHist" objects.

 
package com.myapp.accounting.aes.securities.pricehistory.model;

import com.myapp.accounting.dm.model.refdata.securities.MarketDataSecurityPriceHist;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class PriceHistory implements Serializable
{
    private static final long serialVersionUID = 1L;
    

    private List<marketdatasecuritypricehist> history = new ArrayList<marketdatasecuritypricehist>();

    @XmlElementWrapper(name = "historicalprices")
    @XmlElement(name = "price")
    public List<marketdatasecuritypricehist> getHistory()
    {
        return history;
    }

 public void setHistory(List history) {
  this.history = history;
 }
}


Step 4: Define the MarketDataSecurityPriceHist class that holds the relevant attributes.

 
package com.myapp.accounting.dm.model.refdata.securities;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

import javax.persistence.Entity;
import javax.xml.bind.annotation.XmlElement;

@Entity //persistence entity
public class MarketDataSecurityPriceHist implements Serializable 
{
 private static final long serialVersionUID = 1444498748039607997L;

    private String securityCd;
    private Date priceDttm;
    private BigDecimal bidPrice;
    private BigDecimal closePrice;
    private BigDecimal lastPrice;
    private BigDecimal askPrice;
    private String lastUpdatedAction;
    private String LastUpdatedDetailUser;
    private Date lastUpdatedTimeStamp;
    private Date loadTimeStamp;
    private String pricecondition;
    private String recordType;
    private String priceTime;
    private String source;
    
 public MarketDataSecurityPriceHist()  {}

 @XmlElement
 public String getSecurityCd() 
 {
  return securityCd;
 }

 public void setSecurityCd(String securityCd) 
 {
  this.securityCd = securityCd;
 }

 @XmlElement
 public Date getPriceDttm() {
  return priceDttm;
 }

 public void setPriceDttm(Date priceDttm) {
  this.priceDttm = priceDttm;
 }
 
 @XmlElement
 public BigDecimal getBidPrice() {
  return bidPrice;
 }

 public void setBidPrice(BigDecimal bidPrice) {
  this.bidPrice = bidPrice;
 }

 //other setters and getters are omitted 
}


Step 5: Finally, and most importantly the unit test class that uses mockito to mock the PriceHistoryService implementation and spring-test-mvc to mock the controller that returns a json response.

 
package com.myapp.accounting.aes.securities.pricehistory;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.server.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.server.setup.MockMvcBuilders.standaloneSetup;
import static org.springframework.test.web.server.result.MockMvcResultMatchers.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.http.MediaType;

import com.myapp.accounting.aes.securities.pricehistory.controller.PriceHistoryController;
import com.myapp.accounting.aes.securities.pricehistory.model.PriceHistory;
import com.myapp.accounting.aes.securities.pricehistory.service.PriceHistoryService;
import com.myapp.accounting.aes.securities.pricehistory.service.impl.PriceHistoryServiceImpl;
import com.myapp.accounting.dm.model.refdata.securities.MarketDataSecurityPriceHist;

public class PriceHistoryController2Test {

 private PriceHistoryService mockSecurityPriceService;
 private PriceHistoryController controller;

 @Before
 public void setup() {
  controller = new PriceHistoryController();
  mockSecurityPriceService = mock(PriceHistoryServiceImpl.class);
  controller.setSecurityPriceService(mockSecurityPriceService);
 }

 @Test
 public void getPriceHistory() throws Exception {

  when(
    mockSecurityPriceService.getPriceHistory(
      (Integer) Mockito.any(), (Date) Mockito.any()))
    .thenReturn(getPriceHistoryTestData());

  standaloneSetup(controller)
    .build()
    .perform(
      get(
        "/pricehistory?latestUpdatedTimeStamp=26 Jul 211 12:00:00&maxRecords=3000")
        .accept(MediaType.APPLICATION_JSON))
    .andExpect(status().isOk())
    .andExpect(content().type("application/json"))
    .andExpect(jsonPath("$.[0].securityCd").value("test"))
    .andExpect(jsonPath("$.[0].bidPrice").value(12.50))
          .andExpect(jsonPath("$.[0].closePrice").value(12.50));
         
 }

 //mock data that gets returned when getPriceHistory(...) method is called
 private static PriceHistory getPriceHistoryTestData() {

  PriceHistory ph = new PriceHistory();
  List<marketdatasecuritypricehist> history = new ArrayList<marketdatasecuritypricehist>();
  MarketDataSecurityPriceHist md = new MarketDataSecurityPriceHist();
  md.setSecurityCd("test");
  BigDecimal price = new BigDecimal("12.50");
  md.setAskPrice(price);
  md.setBidPrice(price);
  md.setClosePrice(price);
  md.setLastUpdatedAction("SOME_ACTION");
  md.setRecordType("RECORD_TYPE");
  md.setLastUpdatedDetailUser("tesr");
  Calendar cal = Calendar.getInstance();
  cal.set(2010, 01, 01, 00, 00, 00);
  Date date = cal.getTime();
  md.setLastUpdatedTimeStamp(date);
  md.setPriceDttm(date);
  System.out.println(date);
  
  history.add(md);
  ph.setHistory(history);

  return ph;
 }

}

That's all to it for testing an MVC controller. The URL for above JSON RESTful web service will be something like

 
http://localhost:8080/accounting-server/securities/pricehistory?latestUpdatedTimeStamp=26+Jul+2010+12:00:00&maxRecords=3000

and the JSON data returned will be something like

 
[{"securityCd":"XX123","priceDttm":"2012-01-28","bidPrice":125.50,"closePrice":126.60,"lastPrice":124.50,"askPrice":123.80,"lastUpdatedAction":"NO ACTION","lastUpdatedTimeStamp":1327705288015,"loadTimeStamp":88150,"pricecondition":"NO_CONDITION","recordType":null,"priceTime":"10:01:28.150 AM","source":"HiPort","lastUpdatedDetailUser":"arul"},
{"securityCd":"YY321","priceDttm":"2012-01-28","bidPrice":125.50,"closePrice":126.60,"lastPrice":124.50,"askPrice":123.80,"lastUpdatedAction":"NO ACTION","lastUpdatedTimeStamp":1327705288015,"loadTimeStamp":88150,"pricecondition":"NO_CONDITION","recordType":null,"priceTime":"10:01:28.150 AM","source":"HiPort","lastUpdatedDetailUser":"arul"}]




Labels: , ,