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
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.

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 !!
Suraj
Can you add one example with auto generated id for employee.
Marlon Olaya
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.
Nicolas
Excelent post. Thanks!