通过为测试类添加 @springboottest 注解并配合 @testpropertysource 或 @dynamicpropertysource,可以复用 spring 测试上下文。核心思路是利用 junit 5 的缓存机制,在同一个 jvm 进程内共享已初始化的 applicationcontext,从而避免每次测试都重新加载配置和启动容器。

如何配置不同环境的测试属性?
使用 @TestPropertySource 指定外部配置文件,或在代码中通过 @DynamicPropertySource 动态注册属性。这允许在不修改主配置的情况下,为特定测试注入不同的环境变量或数据库连接串。

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
@SpringBootTest
public class UserServiceTest {
@Autowired private UserService userService;
@DynamicPropertySource
static void properties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", () -> "jdbc:h2:mem:testdb");
}
@Test
void testUserCreation() {
// 验证逻辑
}
}
如何隔离不同测试类的上下文?
通过 @DirtiesContext 注解标记测试方法或类,强制 JUnit 在测试结束后销毁当前上下文。这适用于需要重置单例 Bean 状态或清理全局资源的场景,确保后续测试在一个干净的环境中运行。
JUnit 5.13.4 可用于旧项目兼容性排查;5.13 系列引入参数化测试类并改进测试发现诊断。该分支已不受支持,不建议用于生产项目;对应的 Platform 独立运行包为 1.13.4。

import org.springframework.test.context.DirtiesContext;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(SpringExtension.class)
@SpringBootTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class IsolatedTest {
// 每个测试后都会重建上下文
}
基于 @DirtiesContext 的具体影响是什么?
当测试类被标记为 AFTER_EACH_TEST_METHOD 时,JUnit 会在每个测试方法执行完毕后调用 ApplicationContext.close()。这意味着下一个测试方法将触发一次完整的 Spring 容器启动流程,包括所有 Bean 的定义解析、实例化和依赖注入。虽然这保证了测试间的严格隔离,但会显著增加单个测试的执行时间,通常仅用于存在副作用的全局状态变更测试。










