创建 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()
方法。