Reusing spring application context in junit class classes

We have a bunch of JUnit test cases (integration tests), and they are logically grouped into different test classes.

We can load the Spring application context once for each test class and reuse it for all test cases in the JUnit test class, as stated at http://static.springsource.org/spring/docs/current/spring-framework-reference/ html / testing.html

However, we are just wondering if there is a way to load the Spring application context only once for a bunch of JUnit test classes.

FWIW, we use Spring 3.0.5, JUnit 4.5 and use Maven to create the project.

+51
spring spring-test junit junit4
Dec 14 '11 at 9:17
source share
2 answers

Yes, it is quite possible. All you have to do is use the same locations attributes in your test classes:

 @ContextConfiguration(locations = "classpath:test-context.xml") 

Spring caches application contexts with the locations attribute, so if locations appears a second time, Spring uses the same context rather than creating a new one.

I wrote an article about this feature: Accelerating Spring Integration Tests . It is also described in detail in the Spring documentation: 9.3.2.1 Context-sensitive management and caching .

This has an interesting implication. Since Spring does not know when JUnit is complete, it caches the entire context permanently and closes them using the JVM hookdown. This behavior (especially when you have many test classes with different locations ) can lead to excessive memory usage, memory leaks, etc. Another advantage of the cache context.

+63
Dec 14 '11 at 9:22 a.m.
source share

To add to Tomasz Nurkiewicz's answer , from Spring 3.2.2 @ContextHierarchy you can use annotation to have a separate, connected multiple context structure. This is useful when several test classes want to share (for example) in-memory database settings (datasource, EntityManagerFactory, tx manager, etc.).

For example:

 @ContextHierarchy({ @ContextConfiguration("/test-db-setup-context.xml"), @ContextConfiguration("FirstTest-context.xml") }) @RunWith(SpringJUnit4ClassRunner.class) public class FirstTest { ... } @ContextHierarchy({ @ContextConfiguration("/test-db-setup-context.xml"), @ContextConfiguration("SecondTest-context.xml") }) @RunWith(SpringJUnit4ClassRunner.class) public class SecondTest { ... } 

Using this setting, a context that uses "test-db-setup-context.xml" will be created only once, but the beans inside it can be entered into a separate unit test context

More about the manual: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html#testcontext-ctx-management (search " context hierarchy ")

+22
Apr 11 '14 at 5:55
source share



All Articles