Clean the Spring Context between tests

When running a JUnit test with the SpringJUnit4ClassRunner the Spring context is specified with the ContextConfiguration annotation.

1
2
3
4
5
6
7
8
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("spring-context.xml")
public class MyTests {
@Test
public void aTest() {
}
}

Creating a Spring Context takes some time depending on the size of the application and the classpath that needs to be scanned. Therefore a Context will be stored in the Spring Context cache so that it can be reused for a different test-case.

Sometimes however your tests will change some values in the Spring Context which may cause other tests to fail. The solution is to clean the Spring Context between tests. This can be done with the DirtiesContext annotation.

To clean the Spring Context after the current test, place the DirtiesContext annotation on the method:

1
2
3
4
5
6
7
8
9
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("spring-context.xml")
public class MyTests {
@Test
@DirtiesContext
public void aTest() {
}
}

To clean the Spring Context after each test in the class, place the DirtiesContext annotation on the class and specify the ClassMode AFTER_EACH_TEST_METHOD:

1
2
3
4
5
6
7
8
9
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("spring-context.xml")
@DirtiesContext(classMode=ClassMode.AFTER_EACH_TEST_METHOD)
public class MyTests {
@Test
public void aTest() {
}
}

If no classMode is specified the default of AFTER_CLASS is used. Which will clean the Spring Context after running all tests in the class:

1
2
3
4
5
6
7
8
9
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("spring-context.xml")
@DirtiesContext
public class MyTests {
@Test
public void aTest() {
}
}