Java – Spring & JUnit | How to disable spring test context caching for a specific test class

cachingjavaspring

My code has many integration tests classes – ServiceTest1, ServiceTest2 … , ServiceTestN.
All tests are executed with spring using the same test context (MyAppContext.xml).

As shown in the snippet below, ServiceTest1 test context requires one of its beans to be overridden, and that change is relevant ONLY for ServiceTest1.

When executed, ServiceTest1 works as expected. However, when executing the other tests (e.g. ServiceTest2 in the snippet) it fails with spring initialization errors, since spring is caching MyAppContext.xml test context, and ServiceTest1 test context manipulation is conflicting with the other tests.

I'm looking for a way to avoid caching of ServiceTest1 test context (such as making its caching key unique, based on @ContextConfiguration).
Note that fully disabling caching is not a wanted solution.

Any ideas?

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class ServiceTest1 {

    // some tests ...

    @Configuration
    @ImportResource({"classpath*:MyAppContext.xml"})
    static class Context {

        @Bean
        @Primary
        ServiceOne serviceOne() {
            // instantiate something ...
        }
    }
}


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:MyAppContext.xml"})
public class ServiceTest2 {

    // some tests ...

}

Thanks!

EDIT:
Spring initialization errors are:

java.lang.IllegalStateException: Failed to load ApplicationContext

Caused by: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from URL location [classpath:/WEB-INF/applicationContext-security]

Offending resource: URL [file:/path/to/MyAppContext.xml]; nested exception is org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Duplicate detected.

Offending resource: class path resource [WEB-INF/applicationContext-security.xml]

Best Answer

Use the @DirtiesContext annotation, add this at the class level.

It will then refresh the spring application context after the test class has executed.

Documentation: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/annotation/DirtiesContext.html