Search code examples
spring-bootintegration-testingjunit5spring-boot-testapplication-shutdown

How to gracefully shutdown Spring boot app, after JUnit 5 integration test


How can I gracefully shut down a Spring Boot application after an integration test when @SpringBootTest does not properly terminate the application?

I'm running integration tests for a Spring Boot application. After the tests finish, the application does not automatically shut down when using the @SpringBootTest annotation, and I have to manually kill the process.

My environment:

  • Spring Boot v: 2.6.2
  • JUnit v: 5.8.1
  • Java v: 17

Example:

@SpringBootTest
public class MyIntegrationTest {

    @Test
    public void testSomething() {
        // Test code
    }
}

Attempts:

  • Explicitly shut down the Spring application using `SpringApplication.exit()`.
  • Using the `@DirtiesContext `annotation.

What could be causing the application to not shut down automatically after the tests, and how can I gracefully resolve this issue? Are there any specific configuration settings or code implementations that I should consider?


Solution

  • It can be caused because of any long-running resources(active threads, db connections... etc) or test configuration issues. Custom configurations or listeners could interfere with the normal shutdown process. Another reason can be with the @SpringBootTest context management or an incorrect @DirtiesContext.

    One way to shutdown is to use in a @AfterEach method:

    @SpringBootTest
    public class MyIntegrationTest {
    
    @Autowired
    private ConfigurableApplicationContext applicationContext;
    
    @Test
    public void testSomething() {
        // Test code
    }
    
    @AfterEach
    public void tearDown() {
        if (applicationContext != null) {
            applicationContext.close();
        }
     }
    }
    

    Note: Consider upgrading to a newer version of Spring Boot and JUnit if possible. There could be bug fixes and improvements related to application shutdown and test execution.