How to force a fresh version of the Spring context BEFORE the test executes How to force a fresh version of the Spring context BEFORE the test executes spring spring

How to force a fresh version of the Spring context BEFORE the test executes


As of Spring 4.2 the DirtiesContext annotation supports the following new phases: BEFORE_CLASS, BEFORE_EACH_TEST_METHOD and BEFORE_METHOD. So you can now do for example:

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(...)@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)public class MyTest {   ..}


Pre-Spring 4.2:

I can only suggest a hack unfortunately - you are right, there does not seem to be a simple way to initialize a new application context rather than using a cached application context. These are some of the workarounds that I can suggest:

  1. Use a slightly different @ContextConfiguration - a quick and dirty way to do that could be to add an @ActiveProfiles annotation to the test class, this way Spring will be forced to cache the context with a new key OR define a dummy context with your existing configuration as imports

  2. A hack, but JUnit 4.11+ allows some level of control over test method ordering, it is possible to have a test method right before your target test method and have the dummy test method annotated with @DirtiesContext, this way when your target method is called a fresh context will be created.


There are several options:

  1. You can create an individual spring context for this test by loading another configuration into it. That way, your test will be completely independent of every other test.
  2. You can create a stripped down configuration for this test. That would achieve the same but be faster.
  3. Create a test suite which runs this test first.