Postman的测试脚本(二)
脚本示例
- 一、前言
- 二、操作变量及发送请求脚本
- 三、示例脚本
-
- 1.Response body:Contains string(检查响应体中是否包含一个字符串)
- 2.Response body:Convert XML body to a JSON Object(将XML格式的响应体转换成JSON对象)
- 3.Response body:Is equal to a string(检查响应体等于一个字符串)
- 4.Response body:JSON value check(检查响应体的JSON值)
- 5.Response headers:Content-Type headers check(检查响应中包含某个header)
- 6.Response time is less than 200ms(检查响应时间,要求小于200ms)
- 7.Status code:Code is 200(要求该接口响应Code为200)
- 8.Status code:Code name has string(要求code名称当中包含每个字符串)
- 9.Status code:Successful POST request(要求Status code符合某种条件)
- 10.Use Tiny Validator for JSON data(使用轻量级验证器)
一、前言
测试脚本在发送请求,并从服务器收到响应后才开始执行。接下来看看Postman提供了那些测试脚本片段。
二、操作变量及发送请求脚本
(1)Set a global variable(设置全局变量)的示例如下:
pm.globals.set("variable_key", "variable_value");
(2)Set an environment variable(设置环境变量)的示例如下:
pm.environment.set("variable_key", "variable_value");
(3)Get a global variable(获取全局变量)的示例如下:
pm.globals.get("variable_key");
(4)Get an environment variable(获取环境变量)的示例如下:
pm.environment.get("variable_key");
(5)Get a variable(获取变量)的示例如下:
pm.variables.get("variable_key");
(6)Clear a global variable(清除全局变量)的示例如下:
pm.globals.unset("variable_key");
(7)Clear an environment variable(清除环境变量)的示例如下:
pm.environment.unset("variable_key");
(8)Send a request(发送一个请求)的示例如下:
pm.sendRequest("https://postman-echo.com/get", function (err, response) {
console.log(response.json());
});
以上8个方法和Pre-request Script中的类似,在此不赘述,下面着重看看几个示例脚本。
三、示例脚本
1.Response body:Contains string(检查响应体中是否包含一个字符串)
具体示例如下:
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("金庸");
});
这里要求接口响应必须包含“金庸”字符串,否则报错,如图所示:
测试结果为FALL,响应体中确实不包含“金庸”字样。
2.Response body:Convert XML body to a JSON Object(将XML格式的响应体转换成JSON对象)
假如响应体是XML格式,将其后转换成JSON对象,在对其进行操作。
var jsonObject = xml2Json(responseBody);
接口示例如下:
GET请求,URL为http://www.weather.com.cn/data/sk/101010100.html(免费接口),这是一个获取天气情况的API,返回结果为XML格式,请求响应如果所示:
控制台输出结果,如图所示:
借助上面的方法将其转换为JSON格式查看,如图所示:
控制台输出如图所示:
3.Response body:Is equal to a string(检查响应体等于一个字符串)
具体示例如下:
pm.test("Body is correct", function () {
pm.response.to.have.body("response_body_string");
});
要求响应体必须等于某个字符串,这里,期望响应体等于“北京”,如图所示:
其结果为FALL,应为响应体是一大段文字,不等于“北京”,如图所示: