Postman应用——测试脚本Test Script

文章目录

  • Test Script脚本
    • Collection
    • Folder
    • Request
  • 解析响应体
  • 断言测试

测试脚本可以在Collection、Folder和Request的Pre-request script 和 Test script中编写,测试脚本可以检测请求响应的各个方面,包括正文、状态代码、头、cookie、响应时间等,只有测试符合自定义的要求后才能通过。

Test Script脚本

Collection

Postman应用——测试脚本Test Script_第1张图片

Folder

Postman应用——测试脚本Test Script_第2张图片

Request

Postman应用——测试脚本Test Script_第3张图片

解析响应体

为了在响应中执行断言,首先需要将数据解析为断言可以使用的JavaScript对象。

  1. 解析JSON
const responseJson = pm.response.json();
  1. 解析xml
const responseXml = xml2Json(pm.response.text());
  1. 解析csv
const parse = require('csv-parse/lib/sync');
const responseCsv = parse(pm.response.text());
  1. 解析HTML
const $ = cheerio.load(pm.response.text());
console.log($.html());

如果不解析成JavaScript对象是不是就不可以断言?当然不是,也可以不解析响应体断言:

// 测试响应体是否包含某个字符串
pm.test("Body contains string", () => {
 	pm.expect(pm.response.text()).to.include("customer_id"); 
}

断言测试

pm对象提供了测试相关功能:

  • pm.test(testName:String, specFunction:Function):Function:测试函数。
  • pm.expect(assertion:*):Function → Assertion:允许在响应数据上做测试,使用ChaiJS expect BDD语法。

可以使用pm.response.to.have.*pm.response.to.be.*来构建断言。

示例:

测试状态码:

pm.test("请求状态码200", function() {
  pm.response.to.have.status(200); 
});
pm.test("请求状态码200", function() {
  pm.expect(pm.response.code).to.eql(200); 
});

测试响应时间:

pm.test("请求响应时间少于200ms", () => {
  pm.expect(pm.response.responseTime).to.be.below(200); 
});

是否满足指定条件:

tests["字符串asdf包含a字符"] = "asdf".includes("a"); //旧的语法(已弃用,不推荐使用)

多断言组合测试:
测试脚本也可以包含多个断言作为单个测试,可以将相关断言组合在一起。如果包含的任一个断言失败,整个测试将失败,所有断言都必须成功,测试才能通过。

pm.test("The response has all properties", () => {
  const responseJson = pm.response.json(); //将响应体body转换成JSON格式
  pm.expect(responseJson.type).to.eql('vip'); // type等于vip
  pm.expect(responseJson.name).to.be.a('string'); // name值的类型为string类型
  pm.expect(responseJson.id).to.have.lengthof(1); // id的长度为1
}

测试结果如下:
Postman应用——测试脚本Test Script_第4张图片

你可能感兴趣的:(Postman,postman,测试工具)