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:

Example:

@SpringBootTest
public class MyIntegrationTest {

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

Attempts:

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?

Upvotes: 0

Views: 560

Answers (1)

Kevin Luko
Kevin Luko

Reputation: 178

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.

Upvotes: 0

Related Questions