如何在 spring-boot 中的每个测试类之后清除上下文?

问题描述 投票:0回答:1

我正在使用带有 JUnit 5 的 spring-boot 3.0.12。我们在测试执行期间不采用任何形式的并行性。所有测试都是依次执行的。

有人可以告诉我如何在测试类中执行所有测试后清除 spring 上下文吗?

我知道

@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
。在这里我问是否有某种方法可以让我不必在每个用
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
注释的测试类中放置
@SpringBootTest
。 SpringBoot 测试中是否有任何配置可以自动执行此操作,或者有没有办法让我编写一个 TestExecutionListener ,我可以通过编程方式清除上下文?

java spring spring-boot junit5
1个回答
0
投票

您可以实现 TestExecutionListener 类并覆盖 afterTestClass 方法,例如

@Override
public void afterTestClass(TestContext testContext) throws Exception {
    testContext.getApplicationContext().close();
}

另外,将其添加到您的测试属性文件中,addd org.springframework.test.context.TestExecutionListener=com.example.ClearContextTestExecutionListener

om.example.ClearContextTestExecutionListener 应该替换为您的执行侦听器类

© www.soinside.com 2019 - 2024. All rights reserved.