Start JUnit test with fresh Spring Context

6.4k views Asked by At

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();
  }
}
2

There are 2 answers

2
Jérémie B On BEST ANSWER

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

1
OHY On

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