postman使用2-断言
- 断言编写位置:Tests标签
- 断言所用语言:JavaScript
- 断言执行顺序:在响应体数据返回后执行 。
- 断言执行结果查看:Test Results
1、pm对象
pm.test
函数用来生成一个测试,可以输入测试标题,并加入各种断言。断言全部成功则测试成功,某一个断言失败则测试失败;一个请求可以添加多个测试函数。
pm.test(testName:String, specFunction:Function)
接收两个参数: testName 用字符串输入一个测试名称,会显示在最终报告上;specFunction 接收一个回调函数,在该 回调函数内部运行断言语句。
连接符:to,be,been,is,that,which,and,has,have,with,at,of,same
pm.expect
函数,用来生成各种断言;
.expect()
接收一个断言内容(相当于实际结果),可以是任意数据类型;.to
是连接符,用于连接断言与判断;.include()
用于指定断言方式和预期结果。
pm.response
对象中也提供了很多内置的断言语句。pm.response
是指当前请求接收到的响应body
内容
postman内置了一些常用断言
2、常用断言讲解
状态行中的断言:
- 断言状态码:Status code: code is 200(检查请求后返回的状态码 status 为200)
pm.test("Status code is 200", function () {
pm.response.to.have.status(200); //这里填写的200是预期结果,实际结果是请求返回结果
});
- 断言状态消息
pm.test("Status code name has string", function () {
pm.response.to.have.status("OK"); //断言响应状态消息包含OK
});
响应头中的断言:
- 断言响应头中包含:Response headers:Content-Type header check
pm.test("Content-Type is present", function () {
pm.response.to.have.header("Content-Type"); //断言响应头存在"Content-Type"
});
断言响应体(重点)
- 断言响应体中包含XXX字符串:Response body:Contains string
.expect()
接收一个断言内容(相当于实际结果),可以是任意数据类型;.to
是连接符,用于连接断言与判断;.include()
用于指定断言方式和预期结果。
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});
//注解 pm.expect(pm.response.text()).to.include("string") 获取响应文本中包含string
- 断言响应体等于XXX字符串:Response body : is equal to a string
pm.test("Body is correct", function () {
pm.response.to.have.body("response_body_string");
});
//注解 pm.response.to.have.body("response_body_string"); 获取响应体等于response_body_string
- 断言响应体(json)中某个键名对应的值:Response body : JSON value check
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.value).to.eql(100);
});
//注解 var jsonData = pm.response.json() 获取响应体,以json显示,赋值给jsonData .注意:该响应体必须返回是的json,否则会报错
pm.expect(jsonData.value).to.eql(100) 获取jsonData中键名为value的值,然后和100进行比较
响应时间(一般用于性能测试)
- 断言响应时间:Response time is less than 200ms
pm.test("Response time is less than 200ms", function () {
pm.expect(pm.response.responseTime).to.be.below(200); //断言响应时间<200ms
});