Spring Boot控制器Mockito测试入门求助:编写测试用例指导
别担心,新手刚开始写MockMvc测试确实会有点懵,我一步步带你搞定这个控制器的测试!
第一步:确认依赖(Spring Boot项目)
如果你的项目是Spring Boot,spring-boot-starter-test已经包含了Mockito和MockMvc所需的所有依赖,不需要额外添加。如果是普通Spring项目,确保引入了spring-test和mockito-core依赖。
第二步:编写控制器测试类
我们用@WebMvcTest来专门测试Web层(只加载控制器相关的Bean,测试更轻量),用@MockBean来Mock控制器依赖的TestService,避免依赖真实的业务实现。
以下是针对你的TestController的完整测试示例:
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.mockito.Mockito.*; import static org.hamcrest.Matchers.*; import java.util.Arrays; import java.util.List; @WebMvcTest(TestController.class) public class TestControllerTest { // 注入MockMvc,用来模拟HTTP请求和验证响应 @Autowired private MockMvc mockMvc; // Mock掉控制器依赖的TestService,让控制器使用这个模拟实例 @MockBean private TestService testService; @Test public void getsearchDetailCourse_WithValidCourseName_ReturnsExpectedCourseList() throws Exception { // 1. 准备模拟数据:Service要返回的TestDto列表 List<TestDto> mockCourseList = Arrays.asList( new TestDto("Spring Boot入门", "初级"), new TestDto("Spring Cloud进阶", "中级") ); // 2. 告诉Mockito:当调用testService的对应方法(替换成你实际的方法名)并传入"Spring"时,返回模拟数据 // 注意:这里要和你控制器中调用的TestService方法完全匹配 when(testService.getSearchDetailCourse("Spring")).thenReturn(mockCourseList); // 3. 模拟发送GET请求,带上courseName参数 mockMvc.perform(get("/api/getsearchDetailCourse") .param("courseName", "Spring")) // 4. 验证响应状态码是200 OK .andExpect(status().isOk()) // 5. 验证返回的JSON数组长度是2 .andExpect(jsonPath("$", hasSize(2))) // 6. 验证第一个课程的名称是否正确 .andExpect(jsonPath("$[0].courseName").value("Spring Boot入门")) // 7. 验证第二个课程的级别是否正确 .andExpect(jsonPath("$[1].level").value("中级")); // 8. 额外验证:确保Service的方法确实被调用了1次,参数是"Spring" verify(testService, times(1)).getSearchDetailCourse("Spring"); } // 可选:测试参数为空的场景(如果你的控制器要求courseName必填) @Test public void getsearchDetailCourse_WithEmptyCourseName_ReturnsBadRequest() throws Exception { mockMvc.perform(get("/api/getsearchDetailCourse") .param("courseName", "")) .andExpect(status().isBadRequest()); } }
关键部分解释
@WebMvcTest(TestController.class):只加载和TestController相关的Web层组件,不会启动整个Spring上下文,测试速度更快。@MockBean:创建TestService的模拟实例并注入到Spring容器,这样控制器会自动使用这个模拟对象,不用依赖真实的业务逻辑。mockMvc.perform(...):模拟发送HTTP请求,支持设置URL、参数、请求头等。andExpect(...):验证响应的各种属性,比如状态码、JSON结构和内容(jsonPath用来定位JSON中的具体字段)。when(...).thenReturn(...):定义Mock对象的方法调用行为,指定传入某个参数时返回什么结果。verify(...):验证Mock对象的方法是否被按预期调用(次数、参数是否正确)。
注意事项
- 确保
TestDto有对应的getter方法,Spring的JSON序列化依赖getter来读取字段值。 - 替换示例中
testService.getSearchDetailCourse为你实际的TestService方法名,要和控制器中调用的完全一致。 - 如果你的
@RequestParam设置了required=false,需要调整空参数场景的测试逻辑。
内容的提问来源于stack exchange,提问作者suryakumar101987
相关产品推荐
相关产品推荐

