简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM