- Spring Boot & H2 - Home
- Spring Boot & H2 - Overview
- Spring Boot & H2 - Environment Setup
- Spring Boot & H2 - Project Setup
- Spring Boot & H2 - REST APIs
- Spring Boot & H2 - H2 Console
Spring Boot & H2 Examples
- Spring Boot & H2 - Add Record
- Spring Boot & H2 - Get Record
- Spring Boot & H2 - Get All Records
- Spring Boot & H2 - Update Record
- Spring Boot & H2 - Delete Record
- Spring Boot & H2 - Unit Test Controller
- Spring Boot & H2 - Unit Test Service
- Spring Boot & H2 - Unit Test Repository
Spring Boot & H2 Useful Resources
Spring Boot & H2 - Unit Test Controller
Overview
As in previous chapter we've completed our REST APIs. Now let's create the following structure in src/main/test folder.
com.tutorialspoint.controller.EmployeeControllerTest − A Unit Tester Class to unit test all methods of EmployeeController.
com.tutorialspoint.repository.EmployeeRepositoryTest − A Unit Tester Class to unit test all methods of EmployeeRepository.
com.tutorialspoint.service.EmployeeServiceTest − A Unit Tester Class to unit test all methods of EmployeeService.
SprintBootH2ApplicationTests class is already present. We need to create the above packages and relevant classes.
EmployeeControllerTest
To test a REST Controller, we need the following annotation and classes −
@ExtendWith(SpringExtension.class) − Mark the class to run as test case using SpringExtension class.
@SpringBootTest(classes = SprintBootH2Application.class) − Configure the Spring Boot application.
@AutoConfigureMockMvc − To automatically configure the MockMVC to mock HTTP Requests and Response.
@Autowired private MockMvc mvc; − MockMvc object to be used in testing.
@MockBean private EmployeeController employeeController − EmployeeController mock object to be tested.
EmployeeControllerTest.java
Following is the complete code of EmployeeControllerTest class.
package com.tutorialspoint.controller;
import static org.hamcrest.core.Is.is;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doNothing;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.springboot_h2.SpringbootH2Application;
@SpringBootTest(classes = SpringbootH2Application.class)
@AutoConfigureMockMvc
public class EmployeeControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private EmployeeController employeeController;
@Test
public void testGetAllEmployees() throws Exception {
Employee employee = getEmployee();
List<Employee> employees = new ArrayList<>();
employees.add(employee);
given(employeeController.getAllEmployees()).willReturn(employees);
mvc.perform(get("/emp/employees").contentType(APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(jsonPath("$[0].name", is(employee.getName())));
}
@Test
public void testGetEmployee() throws Exception {
Employee employee = getEmployee();
given(employeeController.getEmployee(1)).willReturn(employee);
mvc.perform(get("/emp/employee/" + employee.getId()).contentType(APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(jsonPath("name", is(employee.getName())));
}
@Test
public void testDeleteEmployee() throws Exception {
Employee employee = getEmployee();
doNothing().when(employeeController).deleteEmployee(1);
mvc.perform(delete("/emp/employee/" + employee.getId()).contentType(APPLICATION_JSON))
.andExpect(status().isOk()).andReturn();
}
@Test
public void testAddEmployee() throws Exception {
Employee employee = getEmployee();
doNothing().when(employeeController).addEmployee(employee);
mvc.perform(post("/emp/employee").content(asJson(employee)).contentType(APPLICATION_JSON))
.andExpect(status().isOk()).andReturn();
}
@Test
public void testUpdateEmployee() throws Exception {
Employee employee = getEmployee();
doNothing().when(employeeController).updateEmployee(employee);
mvc.perform(put("/emp/employee").content(asJson(employee)).contentType(APPLICATION_JSON))
.andExpect(status().isOk()).andReturn();
}
private Employee getEmployee() {
Employee employee = new Employee();
employee.setId(1);
employee.setName("Mahesh");
employee.setAge(30);
employee.setEmail("mahesh@test.com");
return employee;
}
private static String asJson(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Run the test cases.
Run the Test cases using Run As > Maven Test.
[INFO] Scanning for projects... ... [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running com.tutorialspoint.controller.[1mEmployeeControllerTest[m 21:03:09.324 [main] INFO org.springframework.boot.devtools.restart.RestartApplicationListener -- Restart disabled due to context in which it is running . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v3.5.6) 2025-10-01T21:03:09.662+05:30 INFO 46276 --- [springboot-h2] [ main] c.t.controller.EmployeeControllerTest : Starting EmployeeControllerTest using Java 21.0.6 with PID 46276 (started by mahes in D:\Projects\springboot-h2) 2025-10-01T21:03:09.663+05:30 INFO 46276 --- [springboot-h2] [ main] c.t.controller.EmployeeControllerTest : No active profile set, falling back to 1 default profile: "default" 2025-10-01T21:03:10.282+05:30 INFO 46276 --- [springboot-h2] [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode. 2025-10-01T21:03:10.326+05:30 INFO 46276 --- [springboot-h2] [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 33 ms. Found 1 JPA repository interface. ... 2025-10-01T21:03:15.338+05:30 INFO 46276 --- [springboot-h2] [ main] c.t.s.SpringbootH2ApplicationTests : Started SpringbootH2ApplicationTests in 0.48 seconds (process running for 7.078) [INFO] [1;32mTests run: [0;1;32m1[m, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.511 s -- in com.tutorialspoint.springboot_h2.[1mSpringbootH2ApplicationTests[m [INFO] [INFO] Results: [INFO] [INFO] [1;32mTests run: 6, Failures: 0, Errors: 0, Skipped: 0[m [INFO] [INFO] [1m------------------------------------------------------------------------[m [INFO] [1;32mBUILD SUCCESS[m [INFO] [1m------------------------------------------------------------------------[m [INFO] Total time: 10.893 s [INFO] Finished at: 2025-10-01T21:03:15+05:30 [INFO] [1m------------------------------------------------------------------------[m