Postman的Tests模块
-
断言(Assertions):
pm.expect
:用于断言测试。pm.response.to.have.status(200)
:断言响应状态码为200。- 示例:
pm.test("Status code is 200", function () {
pm.response.to.have.status(200); });
-
访问响应体:
pm.response.json()
:获取JSON格式的响应体。- 示例:
pm.test("Response has valid JSON structure", function () {
var jsonData = pm.response.json(); pm.expect(jsonData).to.have.property('key'); });
-
环境和全局变量:
pm.environment.get('variableName')
:获取环境变量。pm.globals.get('variableName')
:获取全局变量。- 示例:
pm.test("Use environment variable", function () { var token = pm.environment.get("apiToken"); pm.expect(token).to.not.be.empty; });
-
前置脚本和后置脚本:
pm.globals.set('variableName', 'value')
:设置全局变量。pm.environment.set('variableName', 'value')
:设置环境变量。- 示例(前置脚本):
// 设置一个全局变量
pm.globals.set("timestamp", new Date().getTime());
-
循环和条件语句:
for
,while
,if
,else
:基本的循环和条件控制结构。- 示例:
pm.test("Check items in array", function () {
var jsonData = pm.response.json(); for (var i = 0; i < jsonData.length; i++) { pm.expect(jsonData[i]).to.have.property('id'); } });
-
使用Chai断言库:
- Chai是一个断言库,提供了丰富的断言方法。
- 示例:
var chai = require('chai');
var expect = chai.expect; pm.test("Check property value", function () { var jsonData = pm.response.json(); expect(jsonData).to.have.property('status').to.equal('success'); });
-
异步代码:
setTimeout
,async/await
:处理异步操作。- 示例(使用
async/await
):pm.test("Async test example", async function () {var response = await pm.request({ url: "https://api.example.com/data", method: "GET" }); pm.expect(response.json()).to.have.property('data'); });
-
使用Postman的内置函数:
pm.response.to.be.json
:断言响应内容类型为JSON。- 示例:
pm.test("Response is JSON", function () {
pm.response.to.be.json; });
-
错误处理:
try/catch
:捕获和处理错误。- 示例:
pm.test("Error handling", function () {
try { var jsonData = pm.response.json(); pm.expect(jsonData).to.have.property('key'); } catch (e) { pm.expect.fail("Error parsing JSON: " + e.message); } });
当然,让我们构建一个更复杂的实际场景,假设我们正在测试一个电商API,我们需要验证以下内容:
- 响应状态码是否为200。
- 响应体是否为JSON格式。
- 响应体中是否包含特定的字段,例如
userId
、productName
和price
。 price
字段是否大于0。- 响应体中的
productName
是否包含在我们的预期列表中。 - 使用环境变量来动态设置预期的
userId
。 - 使用全局变量来记录测试结果。
实际场景的Postman Tests脚本
// 假设我们有一个环境变量 "userId" 和一个全局变量 "testResult"
let expectedUserId = pm.environment.get("userId"); let expectedProductNames = ["Laptop", "Smartphone", "Headphones"]; // 预期的产品名称列表 let testResult = pm.globals.get("testResult") || []; // 获取全局变量 testResult,如果不存在则初始化为空数组 // Tests pm.test("Response status code is 200", function () { pm.response.to.have.status(200); }); pm.test("Response should be JSON", function () { pm.expect(pm.response.to.have.jsonBody()); }); pm.test("Body contains expected data", function () { const responseJson = pm.response.json(); pm.expect(responseJson).to.have.property('userId'); pm.expect(responseJson).to.have.property('productName'); pm.expect(responseJson).to.have.property('price'); pm.expect(responseJson.price).to.be.above(0); // 价格大于0 }); pm.test("Product name is in the expected list", function () { const responseJson = pm.response.json(); const actualProductName = responseJson.productName; pm.expect(expectedProductNames).to.include(actualProductName); }); pm.test("User ID matches the expected value", function () { const responseJson = pm.response.json(); pm.expect(responseJson.userId).to.eql(expectedUserId)