使用postman进行接口测试时,可以在编写脚本的地方,写javascript代码,作为后置脚本对测试结果进行断言,这样对于测试结果起到很好的判断作用,测试才有效果。写脚本的位置整理如下图(注意:不同版本的软件,写断言脚本的位置可能不同)
下面对于一些常用的断言脚本进行整理汇总:
1.判断接口响应的状态码:Status code: code is 200
pm.test("Status code is 200",function(){pm.response.to.have.status(200)})
2.判断接口响应码是否与预期集合中的某个值一致:
pm.test("Successful POST request",function(){pm.expect(pm.response.code).to.be.oneOf([201,200]);})
3.对响应内容断言:断言响应体中包含某些字段
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});
4对响应结果是json格式的内容,断言json中某个键名对应的值
pm.test("Your test name", function () {
var jsonData = pm.response.json();//
获取响应体,以json显示,赋值给jsonData .注意:该响应体必须返会是的json,否则会报错
pm.expect(jsonData.value).to.eql(100);
//
获取jsonData中键名为value的值,然后和100进行比较
});
5断言响应体等于xxx字符串
pm.test("Body is correct",function(){pm.response.to.have.body("xxxxx")})
6断言响应头包含:content-type
1)断言响应头包含:Response headers:Content-Type header check
pm.test("Content-Type is present", function () {
pm.response.to.have.header("Content-Type");
//断言响应头存在"Content-Type"
});
7对响应速度进行断言:
pm.test("Response time is less than 200ms",function(){pm.expect(pm.response,responseTime).to.be.below(2000;})
8对响应字节大小进行断言:
pm.test("响应字节小于10M",function(){pm.expect(pm.response.responseSize).to.be.below(1024*1024*10)});