简体   繁体   中英

Reload Spring application context after every test

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.

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)

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