我们正在构建一堆 API,但在测试它们时遇到了一个奇怪的问题。
在我们的 swagger 文件中,我们有以下内容:
"CustomerAddress": {
"type": "object",
"properties": {
"id": {
"$ref": "#/components/schemas/StringSettable"
},
这引用了以下内容:
"StringSettable": {
"type": "object",
"properties": {
"hasValue": {
"type": "boolean"
},
"value": {
"type": "string",
"nullable": true
}
},
"additionalProperties": false
},
这一切对我们来说看起来没问题,但是当我们运行 ReadyAPI 测试时,我们收到以下错误:
实例类型(字符串)与任何允许的基本类型不匹配 (允许[“object”])检查的节点:[/id]对应的架构: [/属性/id]
这是 JSON 格式的响应负载:
{
"id" : "thisisanid",
"flat" : "Flat",
"buildingName" : "Building",
"houseNumber" : 11,
"addressLine1" : "Line 1",
"addressLine2" : "Line 2",
"town" : "Town",
"county" : "County",
"locality" : "Locality",
"district" : "District",
"postcode" : "TE57 ING",
"validFrom" : null,
"country" : "United Kingdom",
"isForeignAddress" : false,
"isUnknownAddress" : false,
"addressType" : 1,
"op" : "add"
},
我们尝试将 Swagger 编辑为以下内容:
"id": {
"type": "string",
"nullable": true
}
然后就没有任何问题地通过了,所以不能 100% 确定断言在哪里被绊倒。还有其他人遇到过这种情况吗?
根据模式定义,这无效的原因是:
OpenAPI规范中的id被定义为一个对象:
"StringSettable": {
"type": "object", // <-- it's an object
...
}
但是,请求负载中的 id 被定义为字符串:
{
"id" : "thisisanid", // <-- it's a string
... // other properties
}
在这种情况下,您收到的错误消息非常有意义。
如果您想解决此问题,您有两种选择。第一个你已经发现了,就是重新定义OpenAPI规范中的id类型。
第二个是您需要使用不同的请求负载才能满足架构定义:
{
"id" : {
"hasValue": true,
"value": "thisisanid"
},
... // other properties
}