在Postman中进行断言主要涉及到在请求的“Tests”标签页中编写JavaScript代码,以验证API响应是否符合预期。以下是详细的步骤和常见断言方法:
断言用于验证API响应的状态码、响应体内容、响应头等是否与预期一致,以确保API的正确性和稳定性。
状态码断言
pm.test("Status code is 200", function () { pm.response.to.have.status(200); });
响应体断言
pm.test("Body matches string", function () { pm.expect(pm.response.text()).to.include("string_you_want_to_search"); });
pm.test("JSON value check", function () { var jsonData = pm.response.json(); pm.expect(jsonData.value).to.eql(100); });
响应头断言
pm.test("Content-Type is present", function () { pm.expect(pm.response.headers.get('Content-Type')).to.eql('application/json; charsetutf-8'); });
响应速度断言
pm.test("Response time is less than 200ms", function () { pm.expect(pm.response.responseTime).to.be.below(200); });
在集合测试中,可以通过断言来验证批量执行用例的测试结果,提高工作效率。
以下是一个综合示例,展示了如何在Postman中使用断言进行接口测试:
创建请求
添加断言
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
pm.test("Body contains success", function () {
pm.expect(pm.response.text()).to.include("success");
});
pm.test("JSON value check", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.data.name).to.eql("John Doe");
});
发送请求
查看断言结果
通过这些步骤和方法,你可以在Linux系统上使用Postman进行有效的接口测试和断言,确保API的响应符合预期。