对于Postman中的每一个请求,咱们均可以使用JavaScript语言来开发测试脚本。这也就比如单元测试。咱们先看看Postman的相关界面:json
编写测试脚本api
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 });
咱们能够根据咱们的须要,添加各类各样的测试案例。post
以前在《Postman—脚本介绍》这篇文章中已经说到了,Postman中的脚本是在一个沙箱环境中运行的。这个沙箱环境和Postman自己运行的环境是彻底隔离开的,也就是说,这个沙箱环境给脚本的执行提供了一个上下文环境。这个沙箱环境自己就集成了不少的工具方法,咱们能够在咱们的测试脚本中直接使用这些工具方法。具体的能够参考如下文档:单元测试
为了更提升使用者的测试脚本编写效率,Postman提供了不少的代码片断,咱们能够直接使用这些已经写好的代码片断来完成测试脚本的编写。测试
查看结果this
每次运行请求时Postman都会运行测试。固然,咱们能够选择不查看测试结果!spa
测试结果显示在响应查看器下的“Test Results”选项卡中。选项卡标题显示经过了多少测试.3d
参考:https://www.jellythink.com/archives/179