How do you reset Spring JUnit application context after a test class dirties it? How do you reset Spring JUnit application context after a test class dirties it? spring spring

How do you reset Spring JUnit application context after a test class dirties it?


Use @DirtiesContext to force a reset. For example I have:

@ContextConfiguration(classes={BlahTestConfig.class})@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)public class SomeTest {    @Autowired XXXX xx;    @Autowired YYYY yy;    @Before    public void setUp() {        MockitoAnnotations.initMocks(this);        when(YYYY.newYY()).thenReturn(zz);    }    @Test    public void testSomeTest() {        XX.changeSomething("StringTest");        XX.doSomething();        check_for_effects();    }    @Test    public void testSomeOtherTest() {        XX.changeSomething("SomeotherString");        XX.doSomething();        check_for_effects();    }

From spring docs

DirtiesContext

Indicates that the underlying Spring ApplicationContext has been dirtied (modified)as follows during the execution of a test and should be closed, regardless of whether the test passed:

  • After the current test class, when declared on a class with classmode set to AFTER_CLASS, which is the default class mode.

  • After each test method in the current test class, when declared on aclass with class mode set to AFTER_EACH_TEST_METHOD.

  • After the current test, when declared on a method.

Use this annotation if a test has modified the context (for example, by replacing a bean definition). Subsequent tests are supplied a new context.[Note] Limitations of @DirtiesContext with JUnit 3.8

> In a JUnit 3.8 environment @DirtiesContext is only supported on methods and thus not at the class level.

You can use @DirtiesContext as a class-level and method-level annotation within the same class. In such scenarios, the ApplicationContext is marked as dirty after any such annotated method as well as after the entire class. If the ClassMode is set to AFTER_EACH_TEST_METHOD, the context is marked dirty after each test method in the class.

@DirtiesContextpublic class ContextDirtyingTests {    // some tests that result in the Spring container being dirtied}@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)public class ContextDirtyingTests {    // some tests that result in the Spring container being dirtied}@DirtiesContext@Testpublic void testProcessWhichDirtiesAppCtx() {    // some logic that results in the Spring container being dirtied}

When an application context is marked dirty, it is removed from the testing framework's cache and closed; thus the underlying Spring container is rebuilt for any subsequent test that requires a context with the same set of resource locations.