我对Postman很新,并尝试创建自动化脚本来创建包含JSON Schema的对象。但我收到一个错误,我不知道如何绕过。
你能帮忙吗?
这是我预期的响应脚本:
pm.test("Body is correct", function () {
pm.response.to.have.body("{\"Id\":"+typeId+",\"NamespaceId\":"+namespaceId+",\"Name\":\"Auto Test\",\"DataSchema\":\"\{\n \"firstName\": {\n \"type\": \"string\",\n \"description\": \"The person\u0027s first name.\"\n \}\n}\",\"Code\":\"AUTOTYPE\"}");
});
这是实际的响应(Body):
{
"Id": 1059,
"NamespaceId": 1089,
"Name": "Auto Test",
"DataSchema": "{\r\n \"firstName\": {\r\n \"type\": \"string\",\r\n \"description\": \"The person's first name.\"\r\n }\r\n}",
"Code": "AUTOTYPE"
}
这是我得到的错误:
Body is correct | AssertionError: expected response body to equal '{"Id":1059,"NamespaceId":1089,"Name":"Auto Test","DataSchema":"{\n "firstName": {\n "type": "string",\n "description": "The person\'s first name."\n }\n}","Code":"AUTOTYPE"}' but got '{"Id":1059,"NamespaceId":1089,"Name":"Auto Test","DataSchema":"{\\r\\n \\"firstName\\": {\\r\\n \\"type\\": \\"string\\",\\r\\n \\"description\\": \\"The person\\u0027s first name.\\"\\r\\n }\\r\\n}","Code":"AUTOTYPE"}'
以下是创建脚本的实际部分:
{ "NamespaceId": 1089,
"Name": "Auto Test",
"Code": "AUTOTYPE",
"DataSchema": {
"firstName": {
"type": "string",
"description": "The person's first name."
}
}
}
提前致谢。
附:我试图把更多的\
但然后Postman会抱怨。
我认为问题在于您指定将字符串作为正文,而不是将其与JSON对象进行比较。你现在的设置方式,测试非常脆弱,比需要恕我直言的更多。
多一点编码将为您提供更稳定的解决方案(例如,不依赖于与JSON无关的空白格式):
pm.test("Body is correct", function () {
const jsonData = pm.response.json();
pm.expect(jsonData.Id)
.to.be.a('number', 'Id should be a number')
.that.is.equal(typeId, 'Id should equal typeId');
pm.expect(jsonData.NamespaceId)
.to.be.a('number', 'NamespaceId should be a number')
.that.is.eql(namespaceId);
pm.expect(jsonData.Name).to.equal("Auto Test");
// is this really what you want, i.e. should this be a string?
pm.expect(jsonData.DataSchema).to.be.a('string');
const dataSchema = JSON.parse(jsonData.DataSchema);
pm.expect(dataSchema.firstName.type).to.equal("string");
// ... etc
});
测试中有很多空格。尝试:
pm.response.to.have.body( “{\” ID \ “:” + TYPEID + “\ ”名称空间ID \“: ”+名称空间ID +“ \ ”名称\“:\ ”自动测试\“,\” DataSchema \ “:\”{\ n“firstName \”:{\ n“type \”:\“string \”,\ n“description \”:\“the person \ u0027s firstname。\”\ n} \ n} \ “\ ”代码\“:\ ”AUTOTYPE \“}”);