I use the SpringJUnit4ClassRunner
for writing integration tests. I also use @DirtiesContext
for tests that leave the context in an broken state behind
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 {
..
}
There are several options:
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:
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
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.