测试基础课postman使用分享

postman入门(3)必看

2019-04-30  本文已影响97人  Tourble
测试脚本

使用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 运行集合可以使用:

跑起来一个集合

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)

上一篇 下一篇

猜你喜欢

热点阅读