HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Spring Boot 2 / Spring Boot Test / Spring boot, mockito and junit – unit test service layer

Spring boot, mockito and junit – unit test service layer

Learn to write unit tests for service layer of Spring application using JUnit and Mockito testing frameworks. This tutorial demonstrate spring boot test service layer example.

1. Maven Dependencies

The spring-boot-starter-test dependency includes all required dependencies to create and execute tests.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
</dependency>

If not using spring boot then include following dependencies.

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.15.0</version>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <version>2.15.0</version>
</dependency>

2. Setup

In this example, we are unit testing primarily two classes EmployeeManager and EmployeeDao. As name implies, manager class represents service layer and dao class is interacting with database.

EmployeeManager class has a dependency on EmployeeDao and delegate method calls to get the data which pis finally returned to controller classes.

To test the methods in EmployeeManager, we can create a JUnit test class TestEmployeeManager in below given two ways:

2.1. MockitoJUnitRunner class

MockitoJUnitRunner class automatically initialize all the objects annotated with @Mock and @InjectMocks annotations.

@RunWith(MockitoJUnitRunner.class)
public class TestEmployeeManager {
	
	@InjectMocks
	EmployeeManager manager;
	
	@Mock
	EmployeeDao dao;
	
	//tests	
}

2.2. MockitoAnnotations.initMocks() method

If we are not using the MockitoJUnitRunner class approach, then we can use the static method MockitoAnnotations.initMocks(). This method also, upon initialization of junit tests, initializes the mock objects.

public class TestEmployeeManager {
	
	@InjectMocks
	EmployeeManager manager;
	
	@Mock
	EmployeeDao dao;
	
	@Before
	public void init() {
		MockitoAnnotations.initMocks(this);
	}

	//tests	
}

2.3. @Mock vs @InjectMocks

  • The @Mock annotation creates a mock implementation for the class it is annotated with.
  • @InjectMocks also creates the mock implementation, additionally injects the dependent mocks that are marked with the annotations @Mock into it.

In above example, we have annotated EmployeeManager class with @InjectMocks, so mockito will create the mock object for EmployeeManager class and inject the mock dependency of EmployeeDao into it.

3. JUnit tests using Mockito

Let’s see few examples of writing the junit tests to unit test the service layer methods using mock objects created with mockito.

Few example methods could be getAllEmployees() which will return list of EmployeeVO objects, getEmployeeById(int id) to return a employee by given id; and createEmployee() which will add an employee object and return void.

3.1. Service layer tests

package com.howtodoinjava.demo;

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

import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;

import com.howtodoinjava.demo.dao.EmployeeDao;
import com.howtodoinjava.demo.model.EmployeeVO;
import com.howtodoinjava.demo.service.EmployeeManager;

public class TestEmployeeManager {
	
	@InjectMocks
	EmployeeManager manager;
	
	@Mock
	EmployeeDao dao;

	@Before
	public void init() {
		MockitoAnnotations.initMocks(this);
	}
	
	@Test
	public void getAllEmployeesTest()
	{
		List<EmployeeVO> list = new ArrayList<EmployeeVO>();
		EmployeeVO empOne = new EmployeeVO(1, "John", "John", "howtodoinjava@gmail.com");
		EmployeeVO empTwo = new EmployeeVO(2, "Alex", "kolenchiski", "alexk@yahoo.com");
		EmployeeVO empThree = new EmployeeVO(3, "Steve", "Waugh", "swaugh@gmail.com");
		
		list.add(empOne);
		list.add(empTwo);
		list.add(empThree);
		
		when(dao.getEmployeeList()).thenReturn(list);
		
		//test
		List<EmployeeVO> empList = manager.getEmployeeList();
		
		assertEquals(3, empList.size());
		verify(dao, times(1)).getEmployeeList();
	}
	
	@Test
	public void getEmployeeByIdTest()
	{
		when(dao.getEmployeeById(1)).thenReturn(new EmployeeVO(1,"Lokesh","Gupta","user@email.com"));
		
		EmployeeVO emp = manager.getEmployeeById(1);
		
		assertEquals("Lokesh", emp.getFirstName());
		assertEquals("Gupta", emp.getLastName());
		assertEquals("user@email.com", emp.getEmail());
	}
	
	@Test
	public void createEmployeeTest()
	{
		EmployeeVO emp = new EmployeeVO(1,"Lokesh","Gupta","user@email.com");
		
		manager.addEmployee(emp);
		
		verify(dao, times(1)).addEmployee(emp);
	}
}

The unit test results will be like this.

Spring boot mockito junit example
Spring boot mockito junit example

3.2. Service layer class

import java.util.List;

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

import com.howtodoinjava.demo.dao.EmployeeDao;
import com.howtodoinjava.demo.model.EmployeeVO;

@Service
public class EmployeeManager 
{
	@Autowired
	EmployeeDao dao;
	
	public List<EmployeeVO> getEmployeeList() {
		return dao.getEmployeeList();
	}
	
	public EmployeeVO getEmployeeById(int id) {
		return dao.getEmployeeById(id);
	}
	
	public void addEmployee(EmployeeVO employee) {
		dao.addEmployee(employee);
	}
}

3.3. Dao layer class

package com.howtodoinjava.demo.dao;

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

import org.springframework.stereotype.Repository;

import com.howtodoinjava.demo.model.EmployeeVO;

@Repository
public class EmployeeDao {
	
	private Map<Integer, EmployeeVO> DB = new HashMap<>();
	
	public List<EmployeeVO> getEmployeeList() 
	{
		List<EmployeeVO> list = new ArrayList<>();
		if(list.isEmpty()) {
			list.addAll(DB.values());
		}
		return list;
	}
	
	public EmployeeVO getEmployeeById(int id) {
		return DB.get(id);
	}
	
	public void addEmployee(EmployeeVO employee) {
		employee.setEmployeeId(DB.keySet().size() + 1);
		DB.put(employee.getEmployeeId(), employee);
	}
	
	public void updateEmployee(EmployeeVO employee) {
		DB.put(employee.getEmployeeId(), employee);
	}
	
	public void deleteEmployee(int id) {
		DB.remove(id);
	}
}

4. Spring boot mockito example – conclusion

In this mockito tutorial, we learned to unit test the service layer in spring boot applications using JUnit and Mockito. We learned to setup the test class and writing JUnit tests.

We also learned the difference between @Mock and @InjectMocks annotations.

Happy Learning !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Suraj

    January 27, 2020

    Can you add one example with auto generated id for employee.

  2. Marlon Olaya

    October 4, 2019

    Thanks, great post.

    Hi, you have an error in your post, in the last part you said: “We also learned the difference between @Mock and *@InitMocks * annotations.”

    You should change @InitMocks with @InjectMocks.

  3. Nicolas

    June 30, 2019

    Excelent post. Thanks!

Comments are closed on this article!

Search Tutorials

Spring Boot Test

  • Spring Boot – Testing Guide
  • Spring Boot – @SpringBootTest
  • Spring Boot – @WebFluxTest
  • Spring Boot – @RestClientTest
  • Spring Boot – @DataJpaTest
  • Spring Boot – @TestConfiguration
  • Spring Boot – @MockBean
  • Spring Boot – MockMvc
  • Spring Boot – MockMvc Async
  • Spring Boot – TestRestTemplate
  • Spring Boot – JUnit
  • Spring Boot – Junit 5
  • Spring Boot – Test Controller
  • Spring Boot – Test Service Layer
  • Spring Boot – Integration Testing

Spring Boot 2 Tutorial

  • Spring Boot – Introduction
  • Spring Boot – Starter parent
  • Spring Boot – Starter templates
  • Spring Boot – Multi-module project
  • Spring Boot – Annotations
  • Spring Boot – Auto configuration
  • Spring Boot – AOP
  • Spring Boot – Logging
  • Spring Boot – DevTools
  • Spring Boot – WAR Packaging
  • Spring Boot – REST API
  • Spring Boot – CRUD
  • Spring Boot – OAuth2
  • Spring Boot – Testing
  • Spring Boot – RestTemplate
  • Spring Boot – Thymeleaf
  • Spring Boot – Hibernate
  • Spring Boot – DataSource
  • Spring Boot – Error Handling
  • Spring Boot – Caching
  • Spring Boot – Retry
  • Spring Boot – BasicAuth
  • Spring Boot – H2 Database
  • Spring Boot – Ehcache 3.x
  • Spring Boot – Gson
  • Spring Boot – RMI
  • Spring Boot – Send Email
  • Spring Boot – Interview Questions

Spring Boot Tutorial

  • Spring Boot – CommandLineRunner
  • Spring Boot – Configure Jetty
  • Spring Boot – Tomcat Default Port
  • Spring Boot – Context Root
  • Spring Boot – SSL [https]
  • Spring Boot – Get all loaded beans
  • Spring Boot – PropertyEditor
  • Spring Boot – @EnableScheduling
  • Spring Boot – Jersey
  • Spring Boot – SOAP Webservice
  • Spring Boot – SOAP Client
  • Spring Boot – JMSTemplate
  • Spring Boot – REST APIs
  • Spring Boot – JSP View
  • Spring Boot – Actuator endpoints
  • Spring Boot – Role Based Security
  • Spring Boot – RSS / ATOM Feed
  • Spring Boot – Ehcache 2.x

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)