介绍
在这个项目中,你将学习如何使用 JUnit 5 和 Mockito 为学生管理模块创建单元测试。该项目包括两个主要任务:为 StudentServiceImpl 类创建测试以及为 StudentController 类创建测试。
🎯 任务
在这个项目中,你将学习:
- 如何创建一个
ServiceTests.java文件,使用 JUnit 5 测试StudentServiceImpl类 - 如何创建一个
ControllerTests.java文件,使用 JUnit 5 和 Mockito 测试StudentController类 - 如何使用 Spring Boot 测试功能,如
@SpringBootTest和@MockBean,来加载必要的组件并创建用于测试的模拟对象 - 如何编写测试用例来验证
StudentServiceImpl类中queryStudents()、insertStudent()和deleteStudent()方法的功能 - 如何编写测试用例来验证
StudentController类中getStudents()、getStudent()和modifyStudent()方法的功能
🏆 成果
完成这个项目后,你将能够:
- 使用 JUnit 5 和 Mockito 为 Spring Boot 应用程序设置单元测试
- 使用 Spring Boot 测试功能来加载必要的组件并创建用于测试的模拟对象
- 编写有效的测试用例,以确保服务层和控制层实现的正确性
- 使用断言来验证被测试方法的预期行为
创建 ServiceTests.java 文件
在这一步中,你将学习如何创建 ServiceTests.java 文件,使用 JUnit 5 测试 StudentServiceImpl 类。
- 打开你的 IDE,导航到项目中的
/test/java/org/labex/springboottesting目录。 - 创建一个名为
ServiceTests.java的新 Java 文件。 - 在
ServiceTests.java文件中,添加以下代码:
package org.labex.springboottesting;
import org.junit.jupiter.api.Test;
import org.labex.springboottesting.service.StudentServiceImpl;
import org.labex.springboottesting.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@SpringBootTest(classes = StudentServiceImpl.class)
class ServiceTests {
@Autowired
private StudentServiceImpl service;
@Test
void testQueryStudents() {
// 测试服务的 queryStudents() 方法,以确保正确检索数据。
List<Student> result = service.queryStudents();
// 断言返回列表的大小与预期大小匹配。
assertEquals(3, result.size());
}
@Test
void testInsertStudent() {
// 创建一个示例学生对象以进行插入。
Student student = new Student("1", "test", 18, "male");
// 测试服务的 insertStudent() 方法,以确保插入成功。
Boolean result = service.insertStudent(student);
// 断言插入操作成功。
assertTrue(result);
}
@Test
void testDeleteStudent() {
// 测试服务的 deleteStudent() 方法,以确保删除成功。
Boolean result = service.deleteStudent("20191001");
// 断言删除操作成功。
assertTrue(result);
}
}
ServiceTests 类使用 @SpringBootTest(classes = StudentServiceImpl.class) 进行注解,以便在测试类中加载 StudentServiceImpl 实现类。该类包含三个测试方法:
testQueryStudents():测试IStudentService接口的queryStudents()方法,以确保返回的学生列表具有预期的大小。testInsertStudent():测试IStudentService接口的insertStudent()方法,以确保学生插入操作成功。testDeleteStudent():测试IStudentService接口的deleteStudent()方法,以确保学生删除操作成功。
创建 ControllerTests.java 文件
在这一步中,你将学习如何创建 ControllerTests.java 文件,使用 Mockito 测试框架来测试 StudentController 类。
- 打开你的 IDE,导航到项目中的
/test/java/org/labex/springboottesting目录。 - 创建一个名为
ControllerTests.java的新 Java 文件。 - 在
ControllerTests.java文件中,添加以下代码:
package org.labex.springboottesting;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.labex.springboottesting.dao.IStudentDAO;
import org.labex.springboottesting.entity.Student;
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.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import java.util.ArrayList;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest // 加载 Spring Boot 应用上下文。
@EnableWebMvc // 启用 Spring Web MVC 功能。
@AutoConfigureMockMvc // 配置 MockMvc 实例。
class ControllerTests {
@Autowired
private MockMvc mockMvc; // 自动装配 MockMvc 实例以模拟 HTTP 请求。
private ObjectMapper objectMapper; // 用于 JSON 转换的 ObjectMapper。
@MockBean // 使用 MockBean 注解为 IStudentDAO 创建一个模拟对象。
private IStudentDAO studentDAO;
@BeforeEach
void setUp() {
// 初始化 ObjectMapper 以在对象和 JSON 之间进行转换。
this.objectMapper = new ObjectMapper();
}
@Test
void testGetStudents() throws Exception {
// 创建示例学生。
Student s1 = new Student("20191001", "John", 18, "Male");
Student s2 = new Student("20191069", "Lily", 19, "Female");
// 创建一个学生列表并将示例学生添加到其中。
ArrayList<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
// 模拟 studentDAO 的行为,使其在调用 findStudentAll() 时返回学生列表。
when(studentDAO.findStudentAll()).thenReturn(list);
// 执行一个 GET 请求以检索所有学生并验证响应。
this.mockMvc.perform(get("/api/v2/students")
.accept("application/json; charset=UTF-8")) // 设置接受头以指定预期的响应类型。
.andDo(print()) // 打印请求和响应详细信息。
.andExpect(status().isOk()) // 验证响应状态是否为 OK (200)。
.andReturn(); // 返回 MvcResult 对象以进行进一步断言。
}
@Test
void testGetStudent() throws Exception {
// 创建一个示例学生。
Student s1 = new Student("20191001", "John", 18, "Male");
// 模拟 studentDAO 的行为,使其在调用 findStudentById("20191001") 时返回示例学生。
when(studentDAO.findStudentById("20191001")).thenReturn(s1);
// 执行一个 GET 请求以通过 ID 检索特定学生并验证响应。
this.mockMvc.perform(get("/api/v2/student/20191001")
.accept("application/json; charset=UTF-8"))
.andDo(print())
.andExpect(status().isOk())
.andReturn();
}
@Test
void testModifyStudent() throws Exception {
// 创建一个示例学生。
Student s1 = new Student("20191001", "John", 18, "Male");
// 将示例学生转换为 JSON 格式。
String content = objectMapper.writeValueAsString(s1);
// 模拟 studentDAO 的行为,使其在调用 updateStudent(any()) 时返回 true。
when(studentDAO.updateStudent(any())).thenReturn(true);
// 执行一个 PUT 请求以修改学生并验证响应。
this.mockMvc.perform(put("/api/v2/student")
.content(content)
.contentType(MediaType.APPLICATION_JSON)
.accept("application/json; charset=UTF-8"))
.andDo(print())
.andExpect(status().isOk())
.andReturn();
}
}
ControllerTests 类使用 @SpringBootTest 注解来加载 Spring Boot 应用上下文,@EnableWebMvc 注解来启用 Spring Web MVC 功能,以及 @AutoConfigureMockMvc 注解来配置 MockMvc 实例。该类包含三个测试方法:
testGetStudents():通过模拟IStudentDAO接口的行为并向/api/v2/students端点执行 GET 请求,来测试StudentController类的getStudents()方法。testGetStudent():通过模拟IStudentDAO接口的行为并向/api/v2/student/20191001端点执行 GET 请求,来测试StudentController类的getStudent()方法。testModifyStudent():通过模拟IStudentDAO接口的行为,将示例学生对象转换为 JSON,并向/api/v2/student端点执行 PUT 请求,来测试StudentController类的modifyStudent()方法。
运行测试
既然你已经创建了 ServiceTests.java 和 ControllerTests.java 文件,那么你可以运行测试来验证 StudentServiceImpl 和 StudentController 类的功能。
- 打开终端或命令提示符,并使用以下命令导航到你的项目目录:
cd ~/project/springboottesting/
- 运行以下命令来执行
ServiceTests类:
mvn test -Dtest=ServiceTests
这将运行 ServiceTests 类中的三个测试方法并显示结果。
- 运行以下命令来执行
ControllerTests类:
mvn test -Dtest=ControllerTests
这将运行 ControllerTests 类中的三个测试方法并显示结果。
你应该会在控制台输出中看到测试结果,包括任何通过或失败的测试。
总结
恭喜你!你已经完成了这个项目。你可以在 LabEx 中练习更多实验来提升你的技能。



