@DirtiesContext does not work with @Nested tests

Viewed 976

After hours of research on Google I still can't figure out how to use @DirtiesContext with @Nestedclasses. Assuming the following Integration Test class :

@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
public class StuffIntegrationTests {

    @Autowired
    private StuffRepository stuffRepository;

    @Autowired
    private WebApplicationContext context;

    private MockMvc mvc;

    // ...

    @BeforeEach
       private void setUp() {
       mvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply(springSecurity())
                .build();
       // ...
       }

    @DisplayName("POST - /stuffs")
    @Nested
    class saveStuff{

        @DisplayName("Return 2xx")
        @Nested
        class Return2xx{

           // some test methods

        @DisplayName("Return 4xx")
        @Nested
        class Return4xx{

          // some tests methods

    }

    @DisplayName("GET - /stuffs/{stuffId}")
    @Nested
    class findStuffById{

        @DisplayName("Return 2xx")
        @Nested
        class Return2xx{

           // some test methods

        @DisplayName("Return 4xx")
        @Nested
        class Return4xx{

          // some tests methods

    }
}

As you can see I want to make the class more readable by spliting it in nested classes by Enpoints and for each Endpoint there are nested classes to split by Http response status.

I tried to use @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) at multiple level and it doesn't clean the Spring Context before each class, The result is the same if I put @DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD) on each methods.

My goals are to clean the Spring Context before each methods of class SaveStuff and clean the context only once at the begin of the class findStuffById

Thanks a lot for your help.

2 Answers

Spring did not provide support for inheriting test configuration from enclosing classes for a JUnit Jupiter @Nested test class until Spring Framework 5.3.

For details, see the @Nested test class configuration section of the Spring reference manual.

For your information, I faced the same issue while using SpringBoot 2.3, and the problem was fixed with SpringBoot 2.4. Sadly, I didn't find anything to make it work for the version 2.3.

Related