1

I wrote two unit test classes using JUnit4. They both run fine separately, but running them one after another (by for example mvn test), the second test fails.

The reason the second test fails is because the first test modified a bean in the first test. The second test wants to use a fresh instance of this bean.

A unit test should be given a new Context for each unit test class. Spring has first-class support for context caching which I would like to disable. How can I configure Spring to restart a new Context for each unit test class?

My test classes are configured as such:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:a.context.xml")
public class AUnitTest {

  @Test
  public void someTestMethod{
    doSomeFancyStuff();
  }
}
Vjeetje
  • 5,314
  • 5
  • 35
  • 57
  • 1
    I don't use Spring for unit testing anymore. Unit tests shouldn't require dependency injection; I want to use mocks. Spring factory takes too long to start up. – duffymo Feb 04 '16 at 20:45
  • Possible duplicate of [I need my Spring Boot WebApplication to restart in JUnit](http://stackoverflow.com/questions/33151702/i-need-my-spring-boot-webapplication-to-restart-in-junit) – kryger Feb 04 '16 at 21:17
  • Just to be clear to anyone else reading this: the above is **not** a unit test. It is by definition an integration test since it is loading a Spring `ApplicationContext`. – Sam Brannen Feb 05 '16 at 12:55
  • When you say "Spring tries to optimise this," what you are referring to is Spring's first-class support for context caching, which just so happens to be fully documented in the [reference manual](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testcontext-ctx-management-caching). – Sam Brannen Feb 05 '16 at 12:58
  • I adjusted the original post with this additional information – Vjeetje Feb 05 '16 at 15:46

2 Answers2

8

You can use @DirtiesContexton a test method (or a test class). The Spring ApplicationContext will be reloaded after the execution of the test.

Jérémie B
  • 10,611
  • 1
  • 26
  • 43
  • Thanks, Spring seems to cache based on the locations param in the ContextConfiguration annotation: @DirtiesContext(classMode=ClassMode.AFTER_CLASS) works for me – Vjeetje Feb 04 '16 at 20:51
  • There is no need to specify `classMode=ClassMode.AFTER_CLASS`. That is the default! Please read the Javadoc for `classMode`. – Sam Brannen Feb 05 '16 at 12:54
1

You can also use Mockito.reset() after you test. This will save you the loading time of the Spring context.

OHY
  • 890
  • 1
  • 8
  • 14
  • I believe this only works when we are writing pure unit test cases instead of using spring context. Of if we are using spring context, this function doesnt actually reset the application context – SaratBhaswanth Mar 09 '22 at 13:23