【问题标题】:How to close the @SpringBootTest context before JVM's shutdown hook is called (once, after all JUnit tests)如何在调用 JVM 的关闭挂钩之前关闭 @SpringBootTest 上下文(一次,在所有 JUnit 测试之后)
【发布时间】:2021-05-21 10:41:48
【问题描述】:

Q.如何在 JUnit 5 停止 JVM(调用使用 addShutdownHook() 添加的钩子)之前关闭通过使用 @SpringBootTest 注释测试类创建的 Spring Boot 上下文?


示例:
假设像这样的bean

@Component
public class SomeBean implements DisposableBean {

    public SomeBean() {
        var hook = new Thread(() -> System.out.println("Shutdown Hook called"));
        Runtime.getRuntime().addShutdownHook(hook);
    }

    @Override
    public void destroy() {
        System.out.println("Destroy called");
    }
}

还有一个像这样的简单 Junit 5 测试:

@SpringBootTest
class TestJvmShutdownHookApplicationTests {

    @Test
    void contextLoads() {
    }

}

如何在 JVM 关闭挂钩之前执行对 destroy() 的调用?

2021-02-18 13:54:24.540  INFO 18928 --- [           main] .a.t.TestJvmShutdownHookApplicationTests : Started TestJvmShutdownHookApplicationTests in 2.378 seconds (JVM running for 3.687)
Shutdown Hook called
2021-02-18 13:54:24.863  INFO 18928 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
Destroy called

背景 it.ozimov:embedded-redis 添加 JVM 关闭钩子并在 bean redisConnectionFactory (Lettuce) 被销毁之前关闭 Redis 服务器。

【问题讨论】:

  • 我相信这描述了非常相似的问题:stackoverflow.com/questions/48702276/…
  • @Viktar Patotski,不,不一样,它不能解决我的问题。我想在所有测试完成后关闭上下文一次,而不是在每个测试或测试类之后。请重新打开。
  • 上下文是缓存的,所以只会关闭一次。如果它在每次测试(或测试类)后关闭,你要么有不同的配置,因此有不同的上下文,或者正在使用@DirtiesContext
  • @M.Deinum,在我目前的情况下,上下文关闭了一次,但是在 JVM 执行关闭挂钩之后(它被 Spring 的 JVM 关闭挂钩关闭)。我希望它在执行 JVM 关闭挂钩之前关闭一次。
  • 关闭钩子的关闭顺序无法保证,因此没有万无一失的方法。我也看不出是什么问题,关机时出现错误,但可以忽略。

标签: java spring junit5 spring-test


【解决方案1】:

目前没有实现此功能的内置支持。

有关更多详细信息,请参阅 Spring Framework 问题跟踪器中的 Close all ApplicationContexts in the TestContext framework after all tests have been executed 问题。

目前,正确关闭 Spring TestContext Framework 缓存的 ApplicationContext 的唯一方法是通过 @DirtiesContext 或调用 TestContext#markApplicationContextDirty(...) 的自定义 TestExecutionListener

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-29
    • 2015-12-27
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多