44

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.

groodt
  • 1,955
  • 15
  • 26
hudi
  • 15,555
  • 47
  • 142
  • 246

1 Answers1

81

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)
groodt
  • 1,955
  • 15
  • 26
  • nice works like a charm thx a lot. There is just one limitation. When I use annotation @Transactional there is still something dirty :) – hudi Nov 08 '12 at 14:02
  • 2
    Glad it worked out. You might want to try the @Rollback annotation on the test method causing you the trouble. It might be a better idea to just split the test up into 2 clases so it doesn't cause the other test to fail. – groodt Nov 09 '12 at 15:55
  • @groodt superb! thanks a lot. Not only did the solution work, but you added an even more sensible solution regarding splitting tests. Btw, I annotated my offending test class with the above and the result, expectedly was a much slower test, but of course, one that works. My specific case: I was using a Spy on a bean that I needed to reset from test to test. – Beezer Aug 26 '22 at 07:48
  • btw, I removed the class level annotation and added the @DirtiesContext to the offending method, and the test run performance is back to normal. – Beezer Aug 26 '22 at 08:10