Postman的Tests模块

  1. 断言(Assertions):

    • pm.expect:用于断言测试。
    • pm.response.to.have.status(200):断言响应状态码为200。
    • 示例:
      pm.test("Status code is 200", function () {
          pm.response.to.have.status(200);
      });
  2. 访问响应体:

    • pm.response.json():获取JSON格式的响应体。
    • 示例:
      pm.test("Response has valid JSON structure", function () {
          var jsonData = pm.response.json();
          pm.expect(jsonData).to.have.property('key');
      });
  3. 环境和全局变量:

    • 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;
      });
  4. 前置脚本和后置脚本:

    • pm.globals.set('variableName', 'value'):设置全局变量。
    • pm.environment.set('variableName', 'value'):设置环境变量。
    • 示例(前置脚本):
      // 设置一个全局变量
      pm.globals.set("timestamp", new Date().getTime());
  5. 循环和条件语句:

    • forwhileifelse:基本的循环和条件控制结构。
    • 示例:
      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');
          }
      });
  6. 使用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');
      });
  7. 异步代码:

    • setTimeoutasync/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');
      });
  8. 使用Postman的内置函数:

    • pm.response.to.be.json:断言响应内容类型为JSON。
    • 示例:
      pm.test("Response is JSON", function () {
          pm.response.to.be.json;
      });
  9. 错误处理:

    • 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,我们需要验证以下内容:

      1. 响应状态码是否为200。
      2. 响应体是否为JSON格式。
      3. 响应体中是否包含特定的字段,例如userIdproductNameprice
      4. price字段是否大于0。
      5. 响应体中的productName是否包含在我们的预期列表中。
      6. 使用环境变量来动态设置预期的userId
      7. 使用全局变量来记录测试结果。

      实际场景的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);
      });
      
      // 将测试结果记录到全局变量
      if (pm.response.code === 200 && pm.testsresults["Response status code is 200"] && pm.testsresults["Response should be JSON"] && pm.testsresults["Body contains expected data"] && pm.testsresults["Product name is in the expected list"] && pm.testsresults["User ID matches the expected value"]) {
          testResult.push({
              status: "success",
              userId: expectedUserId,
              testName: "All tests passed"
          });
      } else {
          testResult.push({
              status: "fail",
              userId: expectedUserId,
              testName: "Some tests failed"
          });
      }
      
      pm.globals.set("testResult", testResult); // 更新全局变量 testResult
      
      // 打印测试结果到控制台
      console.log("Test Results: ", testResult);

      在这个脚本中,我们首先从环境变量中获取userId,并定义了一个预期的产品名称列表。然后,我们编写了五个测试,分别验证响应状态码、响应体格式、响应体字段、产品名称是否在预期列表中以及用户ID是否匹配。最后,我们将测试结果记录到全局变量testResult中,并打印到控制台。

       

       
posted @ 2024-11-29 15:27  我是影子。  Views(40)  Comments(0Edit  收藏  举报