Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading