在Linux系统中使用Postman进行断言设置主要涉及到在Postman的Tests标签页中编写JavaScript代码来验证API响应是否符合预期。以下是详细的步骤和示例:
打开Postman并发送请求:
导航到Tests标签页:
编写断言代码:
tests[]
语法和新版本的pm.test()
和pm.expect()
语法。tests[]
)// 验证状态码是否为200
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
// 验证响应体中是否包含特定字符串
pm.test("Body matches string", function () {
pm.response.to.have.jsonBody('name');
});
// 验证JSON中的某个值是否等于预期的值
pm.test("检查返回的body里面isUserExists的值是否正确", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.isUserExists).to.be.true;
});
pm.test()
和pm.expect()
)// 验证状态码是否为200
pm.test("Status code is 200", function () {
pm.expect(pm.response.code).to.equal(200);
});
// 验证响应体中是否包含特定字符串
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("expected string");
});
// 验证JSON中的某个值是否等于预期的值
pm.test("检查返回的body里面message的值是否正确", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.message).to.eql("success");
});
假设你有一个API响应如下:
{
"code": 200,
"data": {
"id": 156894,
"name": "John Doe"
}
}
你可以使用以下断言来验证响应:
断言状态码:
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
断言响应体中的特定字段:
pm.test("Response body should contain 'id'", function () {
var jsonData = pm.response.json();
pm.expect(jsonData).to.have.property('id');
});
断言响应体中特定字段的值:
pm.test("The value of 'id' should be 156894", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.id).to.eql(156894);
});
断言响应体中的数组长度:
pm.test("The length of the 'data' array should be 3", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.data.length).to.eql(3);
});
编写完断言代码后,发送请求,Postman会自动执行这些断言并在下方显示测试结果。如果所有断言都通过,则测试结果为PASS;如果有任何一个断言失败,则测试结果为FAIL,并显示失败的断言详情。
通过这些步骤和示例,你可以在Linux系统中的Postman里轻松地进行断言设置,确保API响应符合预期。