一、添加测试脚本
当我们在测试时,期望对响应结果或者响应数据做处理时,可以在postman中接口下的test进行脚本编写,以满足自己想要的测试
- 选择某个接口,点击test,即可在输入框内写入需要的脚本
要验证请求返回的数据,可以使用pm.response在测试中使用该对象。使用函数定义测试pm.test,提供名称和返回布尔值(true
或false
)的函数,指示测试是否通过。
- 选择右侧提供的Snippets
- 点击send
- 在响应中的result中我们可以看到我们想要的结果
- test中也可加上一节讲解的一些脚本
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("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.value).to.eql(100);
});
pm.test("Body is correct", function () {
pm.response.to.have.body("response_body_string");
});
pm.test("Content-Type is present", function () {
pm.response.to.have.header("Content-Type");
});
pm.test("Response time is less than 200ms", function () {
pm.expect(pm.response.responseTime).to.be.below(200);
});
示例:pm.test函数的第一个参数是一个文本字符串,它将出现在测试结果输出中。使用它来验证测试。例如,在请求的“测试”选项卡中输入以下内容以测试响应状态代码是否为200
:
pm.test("响应code是200",function(){
pm.response.to.have.status(200);
});
将代码写入test中后,并send接口,在result即可看到,验证的测试结果:
当我们期望的响应code与实际请求的响应code不一致时,Results也会给出对应的结论:
二、测试集合
在集合中可以添加test,与集合关联的测试脚本将在每个请求之后运行。
- 选择集合--Tests
- 将测试脚本写入test中
- 选择-run collection,看一下跑出的结果
- 每个请求中都会运行在集合中编写的脚本
test中还可以编写一些比较复杂的脚本,根据自己的测试需求进行编写即可。