Spring JUnit and Mockito Integration/Configuration and Mock Test

Reading Time: 2 minutes

In this post roll, I’d like to show how to combine Spring, JUnit and Mockito to test a target application. Simply mocking in my definition is to set dummy data for DAO objects. The target source may have accurate data for us to test depending on given data set, in this case where the mocking plays important role in software testing. You can find further readings on the internet for the concepts. I am more interested in exposing the configuration and conducting a simple test case. First of all I’ll give you sample config of my application set, and explain further steps. I’ll walk through giving the source code.

The project hierarchy as follows;

  • src/main/java: where all the interfaces stay
  • src/test/java: where the test classes stay
  • src/test/resources: where spring context configuration stays

Maven Dependency


DatabaseDAO Interface

public interface DatabaseDAO {	
	public String acquireUserUnitDescription(String usernumber);

DatabaseDAOImpl Class

	public String acquireUserUnitDescription(String usernumber) {
		return unitDescription;

DatabaseService Interface

public interface DatabaseService {	
	public String acquireUserUnitDescription(String usernumber);

DatabaseServiceImpl Class

DatabaseDAO databaseDAO;
	public String acquireUserUnitDescription(String usernumber) {
		return databaseDAO.acquireUserUnitDescription(usernumber);

DatabaseDaoTest Class

package com.test.dao;

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

import org.junit.After;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.akbank.service.DatabaseService;

public class DatabaseDAOTest {
	DatabaseService dbService;
	public void setUp() throws Exception {

	public void tearDown() throws Exception {
	public void testMethod(){
		assertEquals("Development", dbService.acquireUserUnitDescription("999332822"));



Here as you I mocked the object and the method “acquireUserUnitDescription” called with “999332822” value, then the returned value will always be “Development”

You don’t have to set the when case in the setup area, you can define it in your method as well.