我编写了一种模式来验证响应正文。并将所有项目设置为“必需”。但是当主体返回空数组时,它直到通过,这应该是失败。架构如下:
var schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "array",
"items": {
"$ref": "#/definitions/MyObject"
},
"definitions": {
"MyObject": {
"type": ["object"],
"properties": {
"transactionId": "integer",
"transactionType": "string",
"bpCode": "string",
"bpId": "string",
"postingDate ": "string",
"dueDate": "string",
"totalAmount": "number",
"balanceDue": "number",
"reconcileAmount": "number",
"debitCredit": "string",
"remarks": "string",
},
"required": ["transactionId", "transactionType", "bpCode", "bpId", "postingDate", "dueDate", "totalAmount", "balanceDue", "reconcileAmount", "debitCredit", "remarks"],
"additionalProperties": false
}
}
};
tests["Valid respong body schema"] = tv4.validate(data.body, schema);
回复如下:
{
"errorCode": null,
"errorMessage": null,
"body": []
}
您应该使用以下方法排除空数组:
"type": "array",
"minItems": 1
"items": {
"$ref": "#/definitions/MyObject"
}
似乎
jens.klose
给出了正确的答案。你可以试试这个:
const Ajv = require('ajv');
const ajv = new Ajv();
const schema = {
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"errorCode": { "type": ["null", "string"] },
"errorMessage": { "type": ["null", "string"] },
"body": {
"type": "array",
"minItems": 1,
"items": {
"$ref": "#/definitions/MyObject"
}
}
},
"required": ["errorCode", "errorMessage", "body"],
"definitions": {
"MyObject": {
"type": ["object"],
"properties": {
"transactionId": { "type": "integer" },
"transactionType": { "type": "string" },
"bpCode": { "type": "string" },
"bpId": { "type": "string" },
"postingDate": { "type": "string" },
"dueDate": { "type": "string" },
"totalAmount": { "type": "number" },
"balanceDue": { "type": "number" },
"reconcileAmount": { "type": "number" },
"debitCredit": { "type": "string" },
"remarks": { "type": "string" }
},
"required": ["transactionId", "transactionType", "bpCode", "bpId", "postingDate", "dueDate", "totalAmount", "balanceDue", "reconcileAmount", "debitCredit", "remarks"],
"additionalProperties": false
}
}
}
};
const validate = ajv.compile(schema);
const valid = validate(pm.response.json());
if (!valid) {
console.log(validate.errors);
pm.test.fail('JSON is invalid');
} else {
console.log('JSON is valid');
}
希望这能达到预期效果。