Spring Boot 3.x+JUnit5:如何自动在测试类后清除Spring上下文?
解决Spring Boot测试类执行后自动清除上下文的两种方案
一、全局配置实现自动清理
Spring Boot测试支持通过全局配置参数,统一设置所有@SpringBootTest类的上下文清理策略,无需在每个测试类上重复添加@DirtiesContext注解。
配置方法
在测试资源目录下的application.properties或application.yml中添加对应配置:
application.properties
spring.test.context.dirties.context.class-mode=AFTER_CLASS
application.yml
spring: test: context: dirties: context: class-mode: AFTER_CLASS
该配置会对所有标注@SpringBootTest的测试类生效,每个测试类的所有测试方法执行完毕后,Spring会自动清理对应的上下文。
二、自定义TestExecutionListener实现编程式清理
如果全局配置无法满足特殊需求,可自定义TestExecutionListener,在测试类执行完成后手动触发上下文清理。
实现步骤
- 编写自定义监听器类,实现
TestExecutionListener接口并重写afterTestClass方法:
import org.springframework.test.context.TestContext; import org.springframework.test.context.TestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; public class AutoDirtiesContextListener implements TestExecutionListener { private final DirtiesContextTestExecutionListener delegate = new DirtiesContextTestExecutionListener(); @Override public void afterTestClass(TestContext testContext) throws Exception { // 标记上下文为已脏并触发清理逻辑 delegate.beforeTestClass(testContext); delegate.afterTestClass(testContext); } }
- 全局注册监听器,有两种方式:
- 继承基础测试类:创建一个抽象基础测试类,添加
@TestExecutionListeners注解,所有业务测试类继承该类即可:import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestExecutionListeners; @SpringBootTest @TestExecutionListeners(listeners = AutoDirtiesContextListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public abstract class BaseTest { } - SPI自动注册:在测试资源目录下创建
META-INF/services/org.springframework.test.context.TestExecutionListener文件,内容为自定义监听器的全类名:
Spring会自动发现并注册该监听器,无需修改任何测试类。com.yourpackage.AutoDirtiesContextListener
- 继承基础测试类:创建一个抽象基础测试类,添加
注意事项
- 由于你采用串行测试模式,上述两种方式均不会引发并发问题,上下文会按测试类执行顺序依次清理。
- 若个别测试类不需要自动清理,可单独添加
@DirtiesContext(classMode = ClassMode.NEVER)覆盖全局配置。
内容的提问来源于stack exchange,提问作者tuk
相关产品推荐
相关产品推荐

