- Spring Boot & H2 教程
- Spring Boot & H2 - 主页
- Spring Boot & H2 - 概述
- Spring Boot & H2 - 环境设置
- Spring Boot & H2 - 项目设置
- Spring Boot & H2 - REST API
- Spring Boot & H2 - H2 控制台
- Spring Boot & H2 示例
- Spring Boot & H2 - 添加记录
- Spring Boot & H2 - 获取记录
- Spring Boot & H2 - 获取所有记录
- Spring Boot & H2 - 更新记录
- Spring Boot & H2 - 删除记录
- Spring Boot & H2 - 单元测试控制器
- Spring Boot & H2 - 单元测试服务
- Spring Boot & H2 - 单元测试存储库
- Spring Boot & H2 有用资源
- Spring Boot & H2 - 快速指南
- Spring Boot & H2 - 有用资源
- Spring Boot & H2 - 讨论
Spring Boot & H2 - 单元测试服务
概述
要测试服务,我们需要使用以下注释和类 −
@ExtendWith(SpringExtension.class) − 使用 SpringExtension 类标识要作为测试用例运行的类。
@SpringBootTest(classes = SprintBootH2Application.class) − 配置 Spring Boot 应用程序。
@MockBean private EmployeeService employeeService − 要进行测试的 EmployeeService 模拟对象。
EmployeeServiceTest.java
以下为 EmployeeServiceTest 类的完整代码。
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.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.tutorialspoint.entity.Employee; import com.tutorialspoint.springboot_h2.SpringbootH2Application; @ExtendWith(SpringExtension.class) @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("[email protected]"); return employee; } }
运行测试用例。
在 Eclipse 中右键单击该文件,然后选择运行 JUnit 测试并验证结果。
广告