目录
1、单元测试(非 Web 上下文)
1.1、引入依赖
1.2 编写单元测试类(示例代码)
2、Spring MVC 控制器测试
2.1、创建控制器及映射方法
2.2 编写控制器测试类
Spring Boot 提供了强大的单元测试和集成测试支持,以简化基于 Spring 的应用程序的测试。下面分别使用 Spring Boot 进行单元测试和 Web 控制器(MVC)测试。
1、单元测试(非 Web 上下文)
1.1 引入依赖
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>1.2 编写单元测试类(示例代码)
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {// 业务服务类Service@Autowiredprivate UserService userService; @Testpublic void testFindUser() {User user = userService.findUserById(1L);// 断言检查user对象是否正确assertNotNull(user);assertEquals("用户名", user.getName());}
}2、Spring MVC 控制器测试
针对 Spring MVC 控制器,Spring Boot 提供了 MockMvc 测试工具来模拟 HTTP 请求,并验证响应。
2.1 创建控制器及映射方法
package com.example.demo.controller;  import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RestController;  @RestController  
public class ExampleController {  @GetMapping("/hello")  public String hello() {  return "Hello, World!";  }  
}2.2 编写控制器测试类
package com.example.demo.controller;  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.test.web.servlet.MockMvc;  
import org.springframework.test.web.servlet.MvcResult;  import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;  
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;  
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;  
import static org.hamcrest.Matchers.equalTo;  @WebMvcTest(ExampleController.class)  
public class ExampleControllerTest {  @Autowired  private MockMvc mockMvc;  @Test  public void testHello() throws Exception {  MvcResult mvcResult = mockMvc.perform(get("/hello"))  .andExpect(status().isOk())  .andExpect(content().string(equalTo("Hello, World!")))  .andReturn();  String contentAsString = mvcResult.getResponse().getContentAsString();  System.out.println(contentAsString); // 输出响应内容,便于调试  }  
}在这个测试类中,我们使用了
@WebMvcTest注解,它告诉 Spring Test 加载 Spring MVC 的基础配置,但是不会加载整个应用上下文,因此它更适合于测试控制器。@Autowired注解用于自动注入MockMvc实例,它提供了模拟 HTTP 请求并验证响应的功能。在
testHello方法中,我们使用mockMvc.perform方法发送一个 GET 请求到/hello路径,并使用andExpect方法链来验证响应的状态码和内容。如果测试失败,andExpect方法会抛出异常。
注意:
        在实际项目中,你可能还需要编写其他类型的测试,如集成测试、服务层测试、数据访问层测试等,并可能需要配置不同的测试切片(例如 @DataJpaTest 用于数据访问层测试)。
在编写测试时,请确保该测试是可重复的、独立的,并且尽可能地覆盖所有重要的业务逻辑场景。良好的测试实践有助于提高代码质量,并减少在生产环境中出现问题的风险。
后续有时间,再继续更新集成测试、服务层测试、数据访问层测试等。