Vjeetje
Vjeetje

Reputation: 5384

Start JUnit test with fresh Spring Context

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

Upvotes: 1

Views: 6606

Answers (2)

OHY
OHY

Reputation: 970

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

Upvotes: 1

Jérémie B
Jérémie B

Reputation: 11022

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

Upvotes: 8

Related Questions