Reputation: 1980
Q. How to close the Spring Boot context, created by annotating a test class with @SpringBootTest
, before JUnit 5 stops the JVM (which calls the hooks added with addShutdownHook()
) ?
Example:
Assuming a bean like this
@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");
}
}
and a simple Junit 5 test like this:
@SpringBootTest
class TestJvmShutdownHookApplicationTests {
@Test
void contextLoads() {
}
}
how do I get the call to destroy()
to be performed before the JVM shutdown hook?
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
Background
it.ozimov:embedded-redis
adds a JVM shutdown hook and closes the Redis server before the bean redisConnectionFactory
(Lettuce) is destroyed.
Upvotes: 5
Views: 6042
Reputation: 31197
There is currently no built-in support for achieving this.
For further details see the Close all ApplicationContexts in the TestContext framework after all tests have been executed issue in Spring Framework's issue tracker.
Currently, the only way to properly close an ApplicationContext
cached by the Spring TestContext Framework is via @DirtiesContext
or a custom TestExecutionListener
that invokes TestContext#markApplicationContextDirty(...)
Upvotes: 4