linux

Linux Postman如何使用Tests脚本

小樊
54
2025-09-22 16:17:17
栏目: 智能运维

Linux环境下Postman Tests脚本使用指南

1. 准备工作:安装Postman并配置环境

在Linux系统上使用Postman前,需先完成安装:

2. 编写Tests脚本的基本步骤

2.1 创建请求与集合

2.2 添加Tests脚本

3. 常见Tests脚本示例

Tests脚本主要用于验证响应的正确性,以下是常用场景的示例:

3.1 状态码验证

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200); // 断言响应状态码为200(成功)
});

3.2 响应时间验证

pm.test("Response time is less than 200ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(200); // 断言响应时间小于200毫秒
});

3.3 JSON响应体验证

pm.test("Response body contains expected data", function () {
    const jsonData = pm.response.json(); // 解析JSON响应体
    pm.expect(jsonData).to.have.property("token"); // 断言响应体包含"token"字段
    pm.expect(jsonData.token).to.be.a("string"); // 断言"token"字段为字符串类型
});

3.4 环境变量设置与使用

// 设置环境变量(如将响应中的token存入环境变量)
pm.test("Set environment variable", function () {
    const jsonData = pm.response.json();
    pm.environment.set("auth_token", jsonData.token); // 将token存入环境变量"auth_token"
});

// 使用环境变量(如在后续请求的Headers中添加Authorization)
pm.request.headers.add({
    key: "Authorization",
    value: `Bearer ${pm.environment.get("auth_token")}` // 获取环境变量"auth_token"的值
});

3.5 XML响应体转换与验证

pm.test("Parse XML response", function () {
    const xmlData = pm.response.text(); // 获取XML响应体
    const jsonObj = xml2Json(xmlData); // 转换为JSON对象(Postman内置xml2Json函数)
    pm.expect(jsonObj).to.have.property("root.user.name"); // 断言XML中存在"user.name"节点
});

3.6 断言响应头包含特定字段

pm.test("Response header contains Content-Type", function () {
    pm.expect(pm.response.headers).to.have.property("Content-Type"); // 断言响应头包含"Content-Type"
    pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json"); // 断言"Content-Type"包含"application/json"
});

4. 执行与查看测试结果

5. 高级用法

5.1 批量运行测试(Newman命令行工具)

若需批量执行Collection中的所有请求及脚本,可使用Postman的命令行工具Newman

5.2 调试脚本

6. 脚本管理

0
看了该问题的人还看了