postman入门(3)必看

测试脚本

使用Postman,可以使用JavaScript语言为每个请求编写简单的测试用例辅助运行测试。(下图)

image
编写Postman测试脚本
Postman测试本质上是请求发送后执行JavaScript代码。允许访问pm.response对象
image

脚本示例
// 获取response对象
pm.response.json()
// 获取request对象
JSON.parse(request.data);

// 设置环境变量
pm.environment.set("variable_key", "variable_value");

pm.test(".to.have/not.have.**", function() {
    // 判断这个请求是不是正确的
    pm.response.to.have.status(200);
    // 响应结果包含某个JSON字段
    pm.response.to.have.jsonBody("");
    // 响应结果不包含错误的JSON信息
    pm.response.to.not.hava.jsonBody("error");
});

// 判断返回对象中有没有包含某些字符串
pm.test("Body matches string", function() {
    pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});

// 判断响应时间在**ms内
pm.test("Response time is less than **ms", function(){
    pm.expect(pm.response.responseTime).to.be.below(numbers)
});

// pm.response.to.be*
pm.test("response should be okay to process", function() {
    // 响应结果不是错误的
    pm.response.to.not.be.error;
    // httpCode等于200  info:1**;redirection:3**;clientError:4**;serverError:5**
    pm.response.to.be.ok;
    // 是否有实体response对象(包含任何响应格式)
    pm.response.to.be.withBody;
    // 是否有JSON返回对象;
    pm.response.to.be.json;
});
/*
彩蛋:获取请求体内game_id,应用到响应断言做比较是否相等
*/
var requestJSON = JSON.parse(request.data)
var gameId = requestJSON.game_id
pm.test("whether contain game_id", function() {
    pm.response.json().data.game_id === gameId;
});

Runs
集合是一组请求,可以作为一系列请求一起针对相应的环境运行。当你想要自动化API测试时,运行一个集合是很有必要的。运行一个集合时,将一个接一个地发送集合中的所有请求。当你使用脚本时,可以构建集成测试套件,在API请求之间传递数据,并构建反映API实际用例的工作流。

collection-runner.png
运行集合可以使用:

  • 标题栏中runner按钮(下图)
    image

跑起来一个集合

  • collection or folder:运行一个集合时,集合中的所有请求都按照它们在主应用程序中出现的顺序发送。因此,每个文件夹都会运行,而文件夹内的每个请求都会顺序执行。当选择一个文件夹时,只执行该文件夹,并且只发送该文件夹内的请求。但是,当使用setNextRequest()方法时,就可以更改顺序来更紧密地反映你的工作流。
  • Environment:运行集合时的环境。
  • Iterations:集合将要运行的次数
  • Delay:集合运行中每个请求之间的间隔(以毫秒为单位)。
  • Log responses:限制集合运行时的响应日志记录。默认情况下,所有响应都被记录下来以便调试。对于大型集合,可以更改此设置以提高性能。
  • Data:提供用于收集运行的数据文件。
  • Keep varuavle value:默认情况下,集合运行器中的任何环境更改都不会反映在请求生成器中。

Newman

Newman是Postman的命令行收集运行器。它允许直接从命令行运行和测试一个Postman集合。它的构建考虑到了可扩展性,因此可以轻松地将其与持续集成服务器和构建系统集成。
要运行nuwman首先保证有node.js,下载地址,自行安装。

// 下载完成后,执行命令安装newman
npm install -g newman
// newman常用命令
newman run -h //查看帮助信息
// 指定迭代的次数
newman run path_collection_file.json -n number  
//要为每个迭代提供不同的数据集合 -d指定csv 或json文件
newman run path_collection_file.json -d data.json/.csv 
// --environment 指定环境文件
newman run --environment path_collection_file.json

// 为了导出报告 我们要先下载report
npm install newman-reporter-teamcity
--reporters 接收cli, html, json, junit这几个参数可以一起使用
json: xml; junit: html
--reporter-json-export 
// 完整示例
newman run path_collection.json --environment path_environment.json --reporters cli,html,json,junit --reporter-json-export path\htmlOut.html --reporter-junit-export path\xmlOut.xml --reporter-json-export path\jsonOut.json

postman入门(1)
postman入门(2)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。