springspring-bootspring-restdocs

Spring AutoConfigureRestDocs additional configuration


I am generating documentation using Spring REST docs and I am using the new annotation @AutoConfigureRestDocs instead of explicitly defining in the @BeforeEach method. The below test is currently working.

@WebMvcTest(PayrollController.class)
@AutoConfigureRestDocs
class PayrollControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void testHello() throws Exception {
        this.mockMvc.perform(MockMvcRequestBuilders.get("/api/payroll/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string("hello world"));
    }
}

But now I need to pretty print my response and I don't want to do that in every method. As per spring documentation, there is the option to customize further using RestDocsMockMvcConfigurationCustomizer. I did create a bean of that type as per below:

     @WebMvcTest(PayrollController.class)
        @AutoConfigureRestDocs
        class PayrollControllerTest {
        
            @Configuration
            static class RestDocsConfiguration {
                @Bean
                public RestDocsMockMvcConfigurationCustomizer restDocsMockMvcConfigurationCustomizer() {
                    return configurer -> configurer.operationPreprocessors().withResponseDefaults(Preprocessors.prettyPrint());
                }
            }
         @Autowired
         private MockMvc mockMvc;
    
        @Test
        void testHello() throws Exception {
            this.mockMvc.perform(MockMvcRequestBuilders.get("/api/payroll/hello"))
                    .andExpect(status().isOk())
                    .andExpect(content().string("hello world"));
        }
}

But now all my tests are failing and are returning 404 not found. Can someone help me on this?


Solution

  • The problem is caused by your use of @Configuration. As described in the Spring Boot reference documentation, when your test class has a nested @Configuration class it is used instead of your application's primary configuration. You should use @TestConfiguration on your nested RestDocsConfiguration class instead.