You have claimed twice that @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
does not work; however, the following shows that it works as documented.
import javax.annotation.PreDestroy;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
class MyTest {
@Test
void test1(TestInfo testInfo) {
System.err.println(testInfo.getDisplayName());
}
@Test
void test2(TestInfo testInfo) {
System.err.println(testInfo.getDisplayName());
}
@Configuration
static class Config {
@Bean
MyComponent myComponent() {
return new MyComponent();
}
}
}
class MyComponent {
@PreDestroy
void destroy() {
System.err.println("Destroying " + this);
}
}
Executing the above test class results in output to STDERR similar to the following.
test1(TestInfo)
Destroying MyComponent@dc9876b
test2(TestInfo)
Destroying MyComponent@30b6ffe0
Thus, @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
is indeed how you "clear the application context after each test execution".
Putting @DirtiesContext(classMode = BEFORE_CLASS)
doesn't work with Junit5.
Based on my testing, classMode = BEFORE_CLASS
works with TestNG, JUnit 4, and JUnit Jupiter (a.k.a., JUnit 5).
So, if that does not work in your test class, that would be a bug which you should report to the Spring Team.
Do you have any example where you can demonstrate that not working?
FYI: using classMode = BEFORE_CLASS
would only ever make sense if the context had already been created within the currently executing test suite. Otherwise, you are instructing Spring to close and remove an ApplicationContext
from the cache that does not exist... just before Spring actually creates it.
Regards,
Sam (author of the Spring TestContext Framework)