You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何结合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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 09:33:20