Reload Spring application context after every test

2019-03-09 08:27发布

问题:

I have a test Class which contains 2 test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContextTest.xml" })
@Transactional
@TransactionConfiguration(defaultRollback = true)

public class MyITest extends implements BeanFactoryAware {

    private BeanFactory beanFactory;

    @Test
    public void test1() throws Exception {}

    @Test
    public void test2() throws Exception {}        
}

When I run tests individually I get no errors, but when I run all tests together there is a failure. This failure is due to some tests modifying the application context:

  b = beanFactory.getBean("logDataSource", BasicDataSource.class);
  b.set ...

Is there an option to run this test separately? I just want when test1 start it read all necessary things then run test and then close all necessary things. And then start test2.

回答1:

You can use the @DirtiesContext annotation on the test class that modifies the application context.

Java Doc

Spring documentation

By default, this will mark the application context as dirty after the entire test class is run. If you would like to mark the context as dirty after a single test method, then you can either annotate the test method instead or set the classMode property to AFTER_EACH_TEST_METHOD at your class level annotation.

@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)