Spring Boot 测试详解,包含maven引入依赖、测试业务层类、REST风格测试和Mock测试

发布于:2025-04-17 ⋅ 阅读:(28) ⋅ 点赞:(0)

Spring Boot 测试详解

在这里插入图片描述


1. 测试依赖引入

Spring Boot 默认通过以下 Maven 依赖引入测试工具:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

该依赖包含 JUnit 5MockitoAssertJ 等核心测试库,支持单元测试、集成测试和 Mock 测试。


2. IDE 自动创建测试类

IDE(如 IntelliJ/Eclipse)会自动生成测试类,示例如下:

@SpringBootTest
class Chapter15ApplicationTests {
    @Test
    void contextLoads() {
        // 验证应用上下文是否加载成功
    }
}
  • @SpringBootTest:加载完整的 Spring Boot 应用上下文。
  • @Test:JUnit 5 标注测试方法。

3. 测试注解详解
注解 作用
@SpringBootTest 加载完整的 Spring Boot 应用上下文,支持配置 webEnvironment 等参数。
@Test JUnit 5 标注测试方法。
@Autowired 从 Spring 容器中注入 Bean。
@MockBean 在测试上下文中模拟 Bean(Mockito)。
@WebMvcTest 仅加载 Web 层(Controller),不启动完整上下文。
@DataJpaTest 仅加载 JPA 相关配置,用于数据库测试。

4. 业务层测试

场景:测试 UserServicegetUser() 方法。

@SpringBootTest
class UserServiceTests {
    @Autowired
    private UserService userService;

    @Test
    void testGetUser() {
        User user = userService.getUser(1L);
        Assertions.assertNotNull(user, "用户对象不能为空");
    }
}
  • 关键点
    • 通过 @Autowired 注入业务层 Bean。
    • 使用 Assertions(JUnit 5)或 Assert(JUnit 4)进行断言。

5. REST 风格测试

场景:测试 REST 接口 /user/{id},使用随机端口避免冲突。

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {
    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    void testGetUser() {
        User user = restTemplate.getForObject("/user/{id}", User.class, 1L);
        Assertions.assertNotNull(user, "用户对象不能为空");
    }
}
  • 关键点
    • webEnvironment = RANDOM_PORT:启动随机端口的嵌入式服务器。
    • TestRestTemplate:简化 REST 接口调用。

6. Mock 测试(Mockito)

场景:模拟 ProductServicegetProduct() 方法。

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ProductClientTest {
    @MockBean
    private ProductService productService;

    @Test
    void testMockProduct() {
        Product mockProduct = new Product(1L, "产品名称", "产品描述");
        BDDMockito.given(productService.getProduct(1L))
                  .willReturn(mockProduct);
        Product result = productService.getProduct(1L);
        Assertions.assertNotNull(result, "产品对象不能为空");
    }
}
  • 关键点
    • @MockBean:在 Spring 上下文中替换真实 Bean 为 Mock。
    • given().willReturn():定义 Mock 方法的返回值。
    • Mockito 风格:BDD 风格(given-when-then)或经典风格(when-thenReturn)。

7. 测试类型总结表
测试类型 适用场景 关键注解/工具
业务层测试 业务逻辑验证(Service 层) @SpringBootTest, @Autowired
REST 接口测试 控制器接口(Controller)测试 TestRestTemplate, RANDOM_PORT
Mock 测试 模拟外部依赖(如未实现的服务) @MockBean, Mockito
集成测试 跨层协作测试(如数据库) @DataJpaTest, @Transactional

8. 注意事项
  • Mockito 版本:Spring Boot 2.x 默认集成 Mockito 3.x,需注意语法差异。
  • 测试隔离:Mock 测试需确保模拟行为仅作用于当前测试方法。
  • 随机端口:测试时需通过 LocalServerPort 注入实际端口(如需访问外部 URL)。

通过以上配置和示例,可覆盖 Spring Boot 应用的各类测试场景,提升代码质量和开发效率。


网站公告

今日签到

点亮在社区的每一天
去签到