Testing Spring MVC DAO using Mockito Spring TestContext Framework

Testing Spring MVC DAO using Mockito Spring TestContext Framework

Any enterprise application you work unit testing is mandatory part of it. In this tutorial we will keep focus on doing our unit testing using both popular framework Mockito and Spring TestContext framework. Both framework is good to complete independent unit testing easily. To give brief idea first we will create sample Spring MVC application which will consist of Controller –> Service –> DAO(Getting data from database). Below is final maven project structure:

Note: You could visit previous tutorial to get started with Mockito: Complete unit test using Mockito

Testing Spring MVC DAO using Mockito Spring TestContext Framework

As you see above we call sequence goes to Controller –> Service –> DAO layer. To keep tutorial short I will just show you classes which has been used (If you want to take look interface please download complete project from the bottom link).

  • Dependency in pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javahonk</groupId>
	<artifactId>SpringMVCTestingMockito</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringMVCTestingMockito Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<properties>
		<junit.version>3.8.1</junit.version>
		<SpringVersion>4.0.6.RELEASE</SpringVersion>
		<spring-jdbc.version>4.0.6.RELEASE</spring-jdbc.version>
		<json.version>20140107</json.version>
		<jackson.version>1.9.10</jackson.version>
		<log4j.version>1.2.16</log4j.version>
		<jtds.version>1.2</jtds.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<!-- Spring dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${SpringVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${SpringVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${SpringVersion}</version>
		</dependency>
		<!-- Spring and Transactions -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring-jdbc.version}</version>
		</dependency>

		<!-- Jackson JSON Mapper -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>${json.version}</version>
		</dependency>
		<dependency>
			<groupId>net.sourceforge.jtds</groupId>
			<artifactId>jtds</artifactId>
			<version>${jtds.version}</version>
		</dependency>
		<!-- MySql 5.5 Connector -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.29</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<!-- Mockito -->
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<version>1.9.5</version>
		</dependency>
		<!-- Spring testContext framework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>4.0.6.RELEASE</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>SpringMVCTestingMockito</finalName>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
				<version>3.1</version>
			</plugin>
		</plugins>
	</build>
</project>
  • Controller class:
package com.javahonk.controller;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.javahonk.services.IPersonService;


@Controller
public class SpringMVCController {
	
	@Autowired 
	IPersonService transformService;
	
	private static final Logger logger = Logger.getLogger(SpringMVCController.class);
	
	@RequestMapping(value = "/databasetest")
	public @ResponseBody List<Map<String, Object>> databasetest() {
		
		logger.debug("Enter databasetest method");
		return transformService.selectAllPerson();
	}


}
  • PersonServiceImpl.java ( We will test only one method selectAllPerson where call goes to the database and fetches all person data):
package com.javahonk.services;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.javahonk.dao.IPersonDAO;
import com.javahonk.domain.Person;

public class PersonServiceImpl implements IPersonService{
	
	@Autowired
	IPersonDAO transformDAO;

	@Override
	public int insertPerson(Person person) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int updatePerson(Person person) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void deletePerson(int personID) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public List<Map<String, Object>> selectAllPerson() {
		return transformDAO.selectAllPerson();
	}	

}
  • PersonDAOImpl.java: (One one method implementation has been done selectAllPerson):
package com.javahonk.dao;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import com.javahonk.domain.Person;

public class PersonDAOImpl implements IPersonDAO {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public int insertPerson(Person person) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int updatePerson(Person person) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void deletePerson(int personID) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public List<Map<String, Object>> selectAllPerson() {
		String sql = "SELECT * FROM person";
		List<Map<String, Object>> listOfPerson = jdbcTemplate.queryForList(sql);
		return listOfPerson;
	}


}
  • Test controller class where Spring TestContext framework used:
package com.javahonk.controller;

import static org.junit.Assert.fail;

import java.util.Map;

import org.junit.Test; SpringMVCTestingMockito
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.javahonk.services.IPersonService;

//If you want to load multiple files use below:

/*@ContextConfiguration
(
  {
   "classpath:beans.xml",
   "file:src/main/webapp/WEB-INF/dispatcher-data-servlet.xml",
   "file:src/main/webapp/WEB-INF/dispatcher-servlet.xml"
  }
)*/

@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations={"classpath:dispatcher-servlet.xml"}) // If keep context file in resource folder then user this
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/dispatcher-servlet.xml"}) // Reading context file from WEB-INF folder
public class SpringMVCControllerTestUsingTextContextFramework {
	
	@Autowired
	IPersonService transformService;

	//@Test
	public void testFirstPage() {
		fail("Not yet implemented");
	}

	@Test
	public void testDatabasetest() {
		
		for (Map<String, Object> map : transformService.selectAllPerson()) {
			for (Map.Entry entry : map.entrySet()) {
			    System.out.println("Key:" + entry.getKey() + ",Value: " +  entry.getValue());
			}
		}	
				
	}

	//@Test
	public void testGetSampleJSONData() {
		fail("Not yet implemented");
	}

}
  • To run above unit test right click above class –> Run As –> JUnit you will see data from database as below:

Testing Spring MVC DAO using Mockito Spring TestContext Framework

  • Another unit test class for controller using Mockito framework:
package com.javahonk.controller;

import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;

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

import junit.framework.Assert;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import com.javahonk.services.IPersonService;

@RunWith(MockitoJUnitRunner.class)
public class SpringMVCControllerTestUsingMockito {
	
	@Mock
	IPersonService transformService;

	//@Test
	public void testFirstPage() {
		fail("Not yet implemented");
	}

	@Test
	public void testDatabasetest() {
		
		List<Map<String, Object>> value = new ArrayList<Map<String,Object>>();
		
		Map<String, Object> mapValue = new HashMap<String, Object>();
		mapValue.put("FirstName", "Java");
		mapValue.put("LastName", "Honk");		
		mapValue.put("street", "John St.");
		mapValue.put("city", "NY");
		mapValue.put("state", "NY");
		mapValue.put("country", "USA");
		value.add(mapValue);
		when(transformService.selectAllPerson()).thenReturn(value);
		
		for (Map<String, Object> map : transformService.selectAllPerson()) {
			for (Map.Entry entry : map.entrySet()) {
			    System.out.println("Key:" + entry.getKey() + ",Value: " +  entry.getValue());
			}
		}		
		Assert.assertNotNull(transformService.selectAllPerson());			
	}

	//@Test
	public void testGetSampleJSONData() {
		fail("Not yet implemented");
	}

}
  • Run this test as JUnit you will see below:

Testing Spring MVC DAO using Mockito Spring TestContext Framework

  • That’s it.

download  Download project: SpringMVCTestingMockito

Leave a Reply

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