首页 > 解决方案 > Spring Contracts:如何将字符串集合作为 RequestBody 发送

问题描述

关于如何为使用 @RequestBody 将字符串集合作为参数注释的方法编写合同的问题。我有以下方法:

    @PostMapping(path = "/some/uri", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation("GET with body")
    public Response<Boolean> someMethod(@RequestParam(value = "key") final String key,
                                        @RequestBody final Collection<String> numbers){
        return some logic;
    }

我写了以下合同用于测试目的:


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


Contract.make {
    description "Should return true"
    request {
        method POST()
        url("/some/uri?key=NEW_KEY")
        body'''["12345",
                "00143"]'''
    }
    response {
        status 200
        headers {header 'Content-Type': 'application/json;charset=UTF-8'}
        body '''true'''
    }

我一直收到 415,测试找不到我的方法,我想我的错误可能是我发送字符串集合的方式,我尝试了其他一些选项但没有成功。

标签: javaspringgroovycontract

解决方案


我尝试了上面的建议,但不幸的是它们都没有解决我的问题。我得到 415 的原因是,当我在请求中添加正文时,也在后台对正文的内容类型进行了检查,因此我必须在请求中明确指定正文为 json 格式:

request {
        method POST()
        url("/some/uri?key=NEW_KEY")
        headers {header 'Content-Type': 'application/json;charset=UTF-8'}
        body'''["12345",
                "00143"]'''
    }


推荐阅读