我正在尝试验证响应正文,包括邮递员中的错误。我如何验证下面的回复和文本?
{
"responseHeader": {
"publisherId": "12345",
"responseId": "abbcb15d79d54f5dbc473e502e2242c4abbcb15d79d54f5dbc473e502e224264",
"errors": [
{
"errorCode": "1004",
"errorMessage": "XXXX Not Found"
}
]
}
}
这些是我失败的测试:
tests['response json contains responseHeader'] = _.has(responseJSON, 'responseHeader');
tests['response json contains errors'] = _.has(responseJSON, 'responseHeader.publisherId');
tests["Response has publisher id"] = responseJSON.publisherId === 10003;
在“测试”选项卡中,将响应正文解析为对象,然后使用 JavaScript 执行测试。
var data = JSON.parse(responseBody);
tests["publisherId is 12345"] = data.responseHeader.publisherId === "12345";
看一下Postman站点上的测试示例:
https://www.getpostman.com/docs/postman/scripts/test_scripts
https://www.getpostman.com/docs/postman/scripts/test_examples
您可以使用 Postman 的
expect
方法进行断言,并使用 Ajv
库来验证响应模式。
以下是您需要放入邮递员请求的 Scripts->Post-Response
脚本中的示例。
const Ajv = require('ajv');
const ajv = new Ajv();
const schema = {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Response Schema",
"type": "object",
"properties": {
"responseHeader": {
"type": "object",
"properties": {
"publisherId": {"type": "string", "pattern": "^[0-9]+$"},
"responseId": {"type": "string", "pattern": "^[a-f0-9]+$"},
"errors": {
"type": "array",
"items": {
"type": "object",
"properties": {
"errorCode": {"type": "string", "pattern": "^[0-9]+$"},
"errorMessage": {"type": "string"}
},
"required": ["errorCode", "errorMessage"]
}
}
},
"required": ["publisherId", "responseId", "errors"]
}
},
"required": ["responseHeader"]
};
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');
// Validate each property
const responseHeader = pm.response.json().responseHeader;
pm.expect(responseHeader.publisherId).to.be.a('string');
pm.expect(responseHeader.publisherId).to.match(/^[0-9]+$/);
pm.expect(responseHeader.publisherId).to.be.equal("12345");
pm.expect(responseHeader.responseId).to.be.a('string');
pm.expect(responseHeader.responseId).to.match(/^[a-f0-9]+$/);
pm.expect(responseHeader.errors).to.be.an('array');
pm.expect(responseHeader.errors).to.have.lengthOf(1);
pm.expect(responseHeader.errors[0].errorCode).to.be.a('string');
pm.expect(responseHeader.errors[0].errorCode).to.match(/^[0-9]+$/);
pm.expect(responseHeader.errors[0].errorMessage).to.be.a('string');
}
此脚本将根据架构验证响应,如果响应无效,则测试失败。它还将验证响应的每个属性,如果任何属性无效,则测试失败。