如何结合Spring Boot 3.4新MockMvcTester API使用RestDocs
Spring Boot 3.4 MockMvcTester 结合RestDocs生成文档方案
Spring Boot 3.4的新MockMvcTester流式API确实没有直接提供consumeWith方法对接RestDocs,但可以通过获取原生MvcResult的方式实现文档生成,以下是可行方案:
步骤说明
- 确保项目已引入
spring-restdocs-mockmvc依赖 - 调用MockMvcTester的
exchange()后,通过result()方法获取原生MvcResult对象 - 使用
MockMvcRestDocumentation.document()方法处理该MvcResult,传入原有的RestDocs配置参数
修正后的代码示例
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; // 测试类初始化时配置RestDocs @BeforeEach void setUp(RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcTesters.webAppContextSetup(context, documentationConfiguration(restDocumentation)) .build(); } @Test void findByCustomerNumber() { Customer customer = // 初始化测试数据 var result = mockMvc.get() .uri("/api/customer/{id}", customer.customerNumber()) .exchange(); // 执行断言逻辑 assertThat(result) .hasStatus(HttpStatus.OK) .hasHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE) .bodyJson().convertTo(CustomerApiDTO.class) .isEqualTo(customer); // 生成RestDocs文档 document("findByCustomerNumber", pathParameters( parameterWithName("id") .description("The public customerNumber") ), responseFields( fieldWithPath("customerNumber") .description("The unique public ID"), fieldWithPath("firstname") .description("The first name"), fieldWithPath("lastname") .description("The last name") )).handle(result.result()); }
关键说明
- 先完成流式API的断言逻辑,再单独处理文档生成
- 通过
result.result()获取原生MvcResult,交给RestDocs的document处理器处理 - 原有的RestDocs配置参数(如
pathParameters、responseFields)完全兼容,无需修改
内容的提问来源于stack exchange,提问作者Eiswind
相关产品推荐
相关产品推荐

