测试示例

测试脚本在请求发送并从服务器收到响应后运行。

我们来看一些 Postman 测试的例子。大多数示例在 Postman 代码片段中能找到。你可以根据需要编写多个测试。

设置环境变量

pm.environment.set("variable_key", "variable_value");

将嵌套对象设置为环境变量

var array = [1, 2, 3, 4];
pm.environment.set("array", JSON.stringify(array, null, 2));

var obj = { a: [1, 2, 3, 4], b: { c: 'val' } };
pm.environment.set("obj", JSON.stringify(obj));

获取环境变量

pm.environment.get("variable_key");

获取一个环境变量(其值是一个 JSON 字符串)

// 如果数据来自未知来源,这些语句应该包装在一个 try-catch 块。
var array = JSON.parse(pm.environment.get("array"));
var obj = JSON.parse(pm.environment.get("obj"));

清除一个环境变量

pm.environment.unset("variable_key");

设置一个全局变量

pm.globals.set("variable_key", "variable_value");

获取全局变量

pm.globals.get("variable_key");

清除一个全局变量

pm.globals.unset("variable_key");

获取变量

此函数在全局变量和活动环境之中搜索变量。

pm.variables.get("variable_key");

检查响应体是否包含一个字符串

pm.test("Body matches string", function () {
    pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});

检查响应体是否等于一个字符串

pm.test("Body is correct", function () {
    pm.response.to.have.body("response_body_string");
});

检查 JSON 值

pm.test("Your test name", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.value).to.eql(100);
});

Content-Type 是否存在

pm.test("Content-Type is present", function () {
    pm.response.to.have.header("Content-Type");
});

响应时间是否小于200ms

pm.test("Response time is less than 200ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(200);
});

状态码是否是200

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

代码名称是否包含一个字符串

pm.test("Status code name has string", function () {
    pm.response.to.have.status("Created");
});

成功的POST请求状态代码

pm.test("Successful POST request", function () {
    pm.expect(pm.response.code).to.be.oneOf([201,202]);
});

将 TinyValidator 用于 JSON 数据

var schema = {
 "items": {
 "type": "boolean"
 }
};
var data1 = [true, false];
var data2 = [true, 123];

pm.test('Schema is valid', function() {
  pm.expect(tv4.validate(data1, schema)).to.be.true;
  pm.expect(tv4.validate(data2, schema)).to.be.true;
});

解码base64编码数据

var intermediate,
    base64Content, // assume this has a base64 encoded value
    rawContent = base64Content.slice('data:application/octet-stream;base64,'.length);

intermediate = CryptoJS.enc.Base64.parse(base64content); // CryptoJS is an inbuilt object, documented here: https://www.npmjs.com/package/crypto-js
pm.test('Contents are valid', function() {
  pm.expect(CryptoJS.enc.Utf8.stringify(intermediate)).to.be.true;

发送异步请求

此功能既可以作为预请求和测试脚本。

pm.sendRequest("https://postman-echo.com/get", function (err, response) {
    console.log(response.json());
});

将 XML 体转换为 JSON 对象

var jsonObject = xml2Json(responseBody);

示例数据文件

JSON文件由键/值对组成。

下载 JSON 文件

对于CSV文件,顶行需要包含变量名。

下载 CSV 文件

旧版本 Postman 测试

The older style of writing Postman tests relies on setting values for the special tests object. You can set a descriptive key for an element in the object and then say if it’s true or false. For example, tests["Body contains user_id"] = responsebody.has("user_id"); will check whether the response body contains the user_id string.

You can add as many keys as needed, depending on how many things you want to test for. Under the Tests tab under the response viewer, you can view your test results. The tab header shows how many tests passed, and the keys that you set in the tests variable are listed here. If the value evaluates to true, the test passed.

Setting an environment variable

postman.setEnvironmentVariable("key", "value");

Setting a nested object as an environment variable

var array = [1, 2, 3, 4];
postman.setEnvironmentVariable("array", JSON.stringify(array, null, 2));

var obj = { a: [1, 2, 3, 4], b: { c: 'val' } };
postman.setEnvironmentVariable("obj", JSON.stringify(obj));

Getting an environment variable

postman.getEnvironmentVariable("key");

Getting an environment variable (whose value is a stringified object)

// These statements should be wrapped in a try-catch block if the data is coming from an unknown source.

var array = JSON.parse(postman.getEnvironmentVariable("array"));
var obj = JSON.parse(postman.getEnvironmentVariable("obj"));

Clear an environment variable

postman.clearEnvironmentVariable("key");

Set a global variable

postman.setGlobalVariable("key", "value");

Get a global variable

postman.getGlobalVariable("key");

Clear a global variable

postman.clearGlobalVariable("key");

Check if response body contains a string

tests["Body matches string"] = responseBody.has("string_you_want_to_search");

Convert XML body to a JSON object

var jsonObject = xml2Json(responseBody);

Check if response body is equal to a string

tests["Body is correct"] = responseBody === "response_body_string";

Check for a JSON value

var data = JSON.parse(responseBody);
tests["Your test name"] = data.value === 100;

Content-Type is present (Case-insensitive checking)

tests["Content-Type is present"] = postman.getResponseHeader("Content-Type"); //Note: the getResponseHeader() method returns the header value, if it exists.

Content-Type is present (Case-sensitive)

tests["Content-Type is present"] = responseHeaders.hasOwnProperty("Content-Type");

Response time is less than 200ms

tests["Response time is less than 200ms"] = responseTime < 200;

Response time is within a specific range (lower bound inclusive, upper bound exclusive)

tests["Response time is acceptable"] = _.inRange(responseTime, 100, 1001); // _ is the inbuilt Lodash v3.10.1 object, documented at https://lodash.com/docs/3.10.1

Status code is 200

tests["Status code is 200"] = responseCode.code === 200;

Code name contains a string

tests["Status code name has string"] = responseCode.name.has("Created");

Successful POST request status code

tests["Successful POST request"] = responseCode.code === 201 || responseCode.code === 202;

Use TinyValidator for JSON data

var schema = {
 "items": {
 "type": "boolean"

results matching ""

    No results matching ""