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

Spring Boot 3迁移后Spring RESTDocs请求参数片段缺失求助

问题排查与解决方案

针对Spring Boot 3.0.6 + Spring REST Docs 3.0.0迁移后request-parameters片段缺失的问题,按以下步骤排查:

1. 自定义模板格式与路径适配REST Docs 3.x

Spring REST Docs 3.0默认使用Asciidoctor模板(.adoc扩展名),而旧版本(SB2.7.x)默认使用Mustache模板(.snippet扩展名),这是核心差异点:

  • 若继续使用原Mustache模板:
    在测试配置中显式指定模板格式为Mustache,否则REST Docs会忽略.snippet文件:
    @Bean
    fun mockMvc(context: WebApplicationContext, restDocumentation: RestDocumentationContextProvider): MockMvc {
        return MockMvcBuilders.webAppContextSetup(context)
            .apply(documentationConfiguration(restDocumentation)
                .snippets()
                .withTemplateFormat(TemplateFormat.MUSTACHE)) // 强制启用Mustache模板支持
            .build()
    }
    
  • 若迁移到Asciidoctor模板:
    将原request-parameters.snippet重命名为request-parameters.adoc,并移动到路径src/test/resources/org/springframework/restdocs/asciidoctor/templates/下。

2. 确认测试代码生成了目标片段

检查测试用例中是否调用了requestParameters()方法,该方法是生成request-parameters.adoc的必要条件:

mockMvc.perform(get("/zip-cities-find")
        .param("zipCode", "12345"))
    .andExpect(status().isOk)
    .andDo(document("zip-cities-find",
        requestParameters( // 必须包含此配置才会生成对应片段
            parameterWithName("zipCode").description("目标邮政编码")
        ),
        httpRequest(),
        httpResponse(),
        responseFields(),
        links()
    ))

如果缺少该配置,测试不会生成request-parameters.adoc,Asciidoctor自然会报找不到文件。

3. 确保Gradle任务依赖顺序正确

asciidoctor任务必须在test任务执行完成后再运行,否则片段还未生成就会触发查找失败。在Gradle配置中添加依赖:

tasks.named<AsciidoctorTask>("asciidoctor") {
    dependsOn(tasks.test) // 强制asciidoctor在test任务完成后执行
}

4. 验证片段生成路径

手动执行./gradlew test任务后,检查build/generated-snippets/zip-cities-find/目录下是否存在request-parameters.adoc:

  • 若文件不存在:回到步骤2,确认测试代码是否正确配置了requestParameters();
  • 若文件存在:检查Asciidoctor配置中的snippets属性路径是否正确,确保路径指向build/generated-snippets而非子目录。

内容的提问来源于stack exchange,提问作者Gondri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 17:02:02