简体   繁体   中英

Spring test closes contexts only after all tests in test suite are run

Suppose we have tests written as follows (in separate files):

@SpringBootTest(classes = {SomeBeansProvider.class, FunnyCatBeansProvider.class})
public class CatsTest extends AbstractTestNGSpringContextTests {(...)}

@SpringBootTest(classes = {SomeBeansProvider.class, FunnyCatBeansProvider.class})
public class CatTest2 extends AbstractTestNGSpringContextTests {(...)}

@SpringBootTest(classes = {SomeBeansProvider.class, DogBeansProvider.class})
public class DogsTest extends AbstractTestNGSpringContextTests {(...)}

I don't want to complicate things so let's us all pretend for now that all of these tests print something like "Test #no execution completed.".

Also let's have such method defined in SomeBeansProvider.class

@EventListener(ContextClosedEvent.class)
public void onContextClose(final ContextClosedEvent contextClosedEvent) {
   log.info("Context closed.");
} 

If you execute these tests (using TestNG runner) you will see console output similar to this:

  1. Test 1 execution completed.
  2. Test 2 execution completed.
  3. Test 3 execution completed.
  4. Context closed.
  5. Context closed.

Since CatTest and CatTest2 have identical contexts only one will be created for them, and one additional for DogTest.

The problem is that I want contexts be closed just after they are no longer needed. I wonder if it's possible to automatically group tests somehow during execution so there are no multiple context instances at the same time. So I want output to look similar to this:

  1. Test 1 execution completed.
  2. Test 2 execution completed.
  3. Context closed.
  4. Test 3 execution completed.
  5. Context closed.

Is this even possible?

We can use the below Spring annotation in our test case to make it either at class level or Method-level context close.

@DirtiesContext(classMode=ClassMode.AFTER_EACH_TEST_METHOD)

@DirtiesContext(classMode=ClassMode.AFTER_CLASS)

For your scenario you can do like this, You can use @FixMethodOrder(MethodSorters.NAME_ASCENDING) at class level,and annotate @DirtiesContext(methodMode=ClassMode.AFTER_EACH_TEST_METHOD) at each test case wherever you want to close the context. and keep the all the related test cases either first or last in class according to the Ascending order convention so that they will run consecutively so that they will be using the same context(without @DirtiesContext).

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