How to clear context after each test class in spring-boot?

58 views Asked by At

I am using spring-boot 3.0.12 with JUnit 5. We do not employ any sort of parallelism during test execution. All tests are executed one after another.

Can someone let me know how can I clear the spring context after all the tests are executed in a test class?

I am aware of @DirtiesContext(classMode = ClassMode.AFTER_CLASS). Here I am asking if there exists some way where I do not have to put @DirtiesContext(classMode = ClassMode.AFTER_CLASS) in every test class annotated with @SpringBootTest. Is there any configuration in SpringBoot test which will do this automatically or is there a way for me to write a TestExecutionListener from which I would be able to clear the context programmatically?

2

There are 2 answers

0
JUDE On BEST ANSWER

you can implement the TestExecutionListener class and overide the afterTestClass method like

@Override
public void afterTestClass(TestContext testContext) throws Exception {
    testContext.getApplicationContext().close();
}

Also, add this in you test property file, addd org.springframework.test.context.TestExecutionListener=com.example.ClearContextTestExecutionListener

om.example.ClearContextTestExecutionListener should be the replaced to your execution listener class

0
Warlike On

Alternatively, you can use your own annotation like following

@SpringBootTest
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
@Retention(RetentionPolicy.RUNTIME)
public @interface IntegrationTest {

}

And then, use it instead of @SpringBootTest