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

如何为使用@ModelAttribute参数的端点编写Spring Cloud Contract契约

Spring Cloud Contract 适配@ModelAttribute场景解决方案

兼容性确认

Spring Cloud Contract 2.2.7 完全支持Spring MVC生态的@ModelAttribute注解接收多部分表单数据的场景,无需额外扩展依赖即可编写对应契约。

Groovy 契约编写示例

假设你的BarDto包含name(字符串类型)、age(整型)两个字段,参考契约如下:

package contracts.bar.process

import org.springframework.cloud.contract.spec.Contract

Contract.make {
    request {
        method 'POST'
        urlPath '/bar/process'
        headers {
            contentType('multipart/form-data')
        }
        // 直接按DTO字段声明普通表单参数即可,SCC会自动适配@ModelAttribute绑定逻辑
        formParams {
            parameter('name', regex('[a-zA-Z\u4e00-\u9fa5]{2,20}'))
            parameter('age', regex('[1-9][0-9]?'))
            // 剩余BarDto字段按照实际业务结构补充即可
        }
    }
    response {
        status 200
        body([
            [
                fooId: anyPositiveInt(),
                fooContent: anyNonEmptyString()
                // 按实际返回的Foo对象字段结构补充
            ]
        ])
        headers {
            contentType(applicationJson())
        }
    }
}

注意事项

  • 和@RequestPart场景不同,@ModelAttribute绑定的普通表单字段不需要放在multipart配置块中,直接在formParams块声明即可。
  • 如果BarDto中包含文件类型的字段,仅需在multipart块中声明对应文件参数,其余普通字段仍然保留在formParams中即可正常绑定。
  • 生成的单测会完全复用Spring MVC的参数绑定逻辑,和线上接口实际运行行为一致。

内容的提问来源于stack exchange,提问作者Arek Cegłowski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:57:00