Spring AutoConfigureRestDocs 附加配置 [英] Spring AutoConfigureRestDocs additional configuration
问题描述
我正在使用 Spring REST
文档生成文档,并且我正在使用新的注释 @AutoConfigureRestDocs
而不是在 @BeforeEach
方法中明确定义.以下测试目前正在运行.
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"));
}
}
但现在我需要漂亮地打印我的回复,我不想在每种方法中都这样做.根据 spring 文档,可以选择使用 RestDocsMockMvcConfigurationCustomizer
进一步自定义.我确实创建了一个该类型的 bean,如下所示:
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"));
}
}
但是现在我所有的测试都失败了并且返回 404 not found.有人可以帮助我吗?
But now all my tests are failing and are returning 404 not found. Can someone help me on this?
推荐答案
问题是由于您使用了@Configuration
.如Spring Boot 参考文档,当你的测试类有一个嵌套的 @Configuration
类时,它被用来代替你的应用程序的主要配置.您应该在嵌套的 RestDocsConfiguration
类上改用 @TestConfiguration
.
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.
这篇关于Spring AutoConfigureRestDocs 附加配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!