Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse spring application context across junit test classes

We've a bunch of JUnit test cases (Integration tests) and they are logically grouped into different test classes.

We are able to load Spring application context once per test class and re-use it for all test cases in a JUnit test class as mentioned in http://static.springsource.org/spring/docs/current/spring-framework-reference/html/testing.html

However, we were just wondering if there is a way to load 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 build the project.

like image 606
Ramesh Avatar asked Dec 14 '11 09:12

Ramesh


People also ask

How can you create a shared application context in a JUnit integration test?

How can you create a shared application context in a JUnit integration test. Spring's integration testing support has the following primary goals: To manage Spring IoC container caching between tests. By default, once loaded, the configured ApplicationContext is reused for each test.

Can Spring have multiple application contexts?

You can have two contexts within an application. If you have two contexts each will have its own singleton.

What does SpringBootTest annotation do?

The @SpringBootTest annotation loads the complete Spring application context. In contrast, a test slice annotation only loads beans required to test a particular layer. And because of this, we can avoid unnecessary mocking and side effects.

What is @ContextConfiguration in Spring?

@ContextConfiguration defines class-level metadata that is used to determine how to load and configure an ApplicationContext for integration tests.


1 Answers

Yes, this is perfectly possible. All you have to do is to use the same locations attribute in your test classes:

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

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

I wrote an article about this feature: Speeding up Spring integration tests. Also it is described in details in Spring documentation: 9.3.2.1 Context management and caching.

This has an interesting implication. Because Spring does not know when JUnit is done, it caches all context forever and closes them using JVM shutdown hook. This behavior (especially when you have a lot of test classes with different locations) might lead to excessive memory usage, memory leaks, etc. Another advantage of caching context.

like image 164
Tomasz Nurkiewicz Avatar answered Oct 05 '22 20:10

Tomasz Nurkiewicz