Spring Cloud Contract Verifier生成多余断言的技术问题
解决Spring Cloud Contract Verifier生成多余断言的问题
我帮你排查了下,问题出在契约里matchers的路径配置上。你看你的matchers里用了$[*].name这种带数组通配符[*]的路径,但你的响应体是一个单独的JSON对象,并不是数组结构,这就导致匹配逻辑错位,进而生成了多余的断言。
修正后的契约配置
把matchers里的路径改成针对单个对象的格式,去掉数组通配符[*]即可:
request: method: GET url: /get response: status: 200 body: name: 'Name' code: '123' asOfDate: '1994-05-25T04:00:00.000Z' matchers: body: - path: "$.name" type: by_type - path: "$.code" type: by_regex value: '[0-9]{3}' - path: "$.asOfDate" type: by_regex predefined: iso_date_time
为什么这样改?
$[*]是Spring Cloud Contract用来匹配数组中所有元素的通配符,但你的响应体是{"name":"Name",...}这种单个对象,用$.name才能精准定位到对象里的name字段。路径匹配正确后,生成的测试代码就只会生成对应字段的必要断言,不会有多余内容了。
修正后生成的测试代码片段会类似这样:
// and: DocumentContext parsedJson = JsonPath.parse(response.getBody().asString()); assertThatJson(parsedJson).field("['name']").isInstanceOf(String.class); assertThatJson(parsedJson).field("['code']").matches("[0-9]{3}"); assertThatJson(parsedJson).field("['asOfDate']").matches(".*"); // 对应iso_date_time预定义正则
内容的提问来源于stack exchange,提问作者Keifer
相关产品推荐
相关产品推荐

