测试脚本


测试脚本

使用Postman,你可以使用JavaScript为每个请求编写测试脚本。

编写Postman测试

Postman测试实质上是,在发送请求后执行的JavaScript代码,可以访问pm.response对象。

示例代码

// example using pm.response.to.have
pm.test("response is ok", function () {
    pm.response.to.have.status(200);
});

// example using pm.expect()
pm.test("environment to be production", function () {
    pm.expect(pm.environment.get("env")).to.equal("production");
});

// example using response assertions
pm.test("response should be okay to process", function () {
    pm.response.to.not.be.error;
    pm.response.to.have.jsonBody("");
    pm.response.to.not.have.jsonBody("error");
});

// example using pm.response.to.be*
pm.test("response must be valid and have a body", function () {
     // assert that the status code is 200
     pm.response.to.be.ok; // info, success, redirection, clientError,  serverError, are other variants
     // assert that the response has a valid JSON body
     pm.response.to.be.withBody;
     pm.response.to.be.json; // this assertion also checks if a body  exists, so the above check is not needed
});

代码片段

尽管编写测试时要记住的事情很少,但Postman可以通过在编辑器旁边列出常用的代码片段来简化此过程。

您可以选择要添加的代码段,并在测试编辑器中填充适当的代码。这是快速构建测试用例的好方法。

查看结果

结果显示在响应查看器下的Test选项卡中。标签页眉显示了通过了多少次测试,并在此处列出了测试结果。如果测试评估为真,则测试通过。

将测试脚本添加到集合或文件夹

  • 将测试脚本添加到集合
  • 将测试脚本添加到文件夹