Spring Boot & H2 - Unit Test Service



Overview

To test a Service, 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.

  • @MockBean private EmployeeService employeeService − EmployeeService mock object to be tested.

EmployeeServiceTest.java

Following is the complete code of EmployeeServiceTest class.

package com.tutorialspoint.service;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doNothing;

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

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;

import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.springboot_h2.SpringbootH2Application;

@SpringBootTest(classes = SpringbootH2Application.class)
public class EmployeeServiceTest {
   
   @MockBean
   private EmployeeService employeeService;
   
   @Test
   public void testGetAllEmployees() throws Exception {
      Employee employee = getEmployee();
      List<Employee> employees = new ArrayList<>();
      employees.add(employee);
      given(employeeService.getAllEmployees()).willReturn(employees);
      List<Employee> result = employeeService.getAllEmployees();
      assertEquals(result.size(), 1);
   }
   
   @Test
   public void testGetEmployee() throws Exception {
      Employee employee = getEmployee();
      given(employeeService.getEmployeeById(1)).willReturn(employee);
      Employee result = employeeService.getEmployeeById(1);
      assertEquals(result.getId(), 1);	
   }
   
   @Test
   public void testDeleteEmployee() throws Exception {
      doNothing().when(employeeService).deleteEmployeeById(1);
      employeeService.deleteEmployeeById(1);
      assertTrue(true);
   }
   
   @Test
   public void testSaveOrUpdateEmployee() throws Exception {
      Employee employee = getEmployee();
      doNothing().when(employeeService).saveOrUpdate(employee);	
      employeeService.saveOrUpdate(employee);
      assertTrue(true);
   }
   
   private Employee getEmployee() {
      Employee employee = new Employee();
      employee.setId(1);
      employee.setName("Mahesh");
      employee.setAge(30);
      employee.setEmail("mahesh@test.com");
      return employee;
   }
}

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.service.[1mEmployeeServiceTest[m
2025-10-01T21:26:04.330+05:30  INFO 30384 --- [springboot-h2] [           main] o.s.b.d.r.RestartApplicationListener     : Restart disabled due to context in which it is running

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.5.6)

2025-10-01T21:26:04.364+05:30  INFO 30384 --- [springboot-h2] [           main] c.t.service.EmployeeServiceTest          : Starting EmployeeServiceTest using Java 21.0.6 with PID 30384 (started by mahes in D:\Projects\springboot-h2)
2025-10-01T21:26:04.365+05:30  INFO 30384 --- [springboot-h2] [           main] c.t.service.EmployeeServiceTest          : No active profile set, falling back to 1 default profile: "default"
2025-10-01T21:26:04.519+05:30  INFO 30384 --- [springboot-h2] [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2025-10-01T21:26:04.530+05:30  INFO 30384 --- [springboot-h2] [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 6 ms. Found 1 JPA repository interface.
...
[INFO] [1;32mTests run: [0;1;32m1[m, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.222 s -- in com.tutorialspoint.springboot_h2.[1mSpringbootH2ApplicationTests[m
[INFO] 
[INFO] Results:
[INFO] 
[INFO] [1;32mTests run: 10, Failures: 0, Errors: 0, Skipped: 0[m
[INFO] 
[INFO] [1m------------------------------------------------------------------------[m
[INFO] [1;32mBUILD SUCCESS[m
[INFO] [1m------------------------------------------------------------------------[m
[INFO] Total time:  12.634 s
[INFO] Finished at: 2025-10-01T21:26:06+05:30
[INFO] [1m------------------------------------------------------------------------[m
Advertisements