使用 postman 给 API 写测试

使用 postman 给 API 写测试

Intro

上次我们简单介绍了 使用 postman 测试 API,这次主要来写一些测试用例以检查请求的响应是否符合我们的预期以及如何使用脚本测试

使用 postman 内置的随机变量

postman 内置的有一些产生随机值的变量,在发送请求时随机生成,这样我们可以在请求中随机生成一些用户名,邮箱,公司名称等等,

支持的变量如下,官方文档:https://learning.getpostman.com/docs/postman/variables-and-environments/variables-list/

  • {{$randomZipCode}}

  • {{$randomCity}}

  • {{$randomCityPrefix}}

  • {{$randomCitySuffix}}

  • {{$randomStreetName}}

  • {{$randomStreetAddress}}

  • {{$randomStreetSuffix}}

  • {{$randomStreetPrefix}}

  • {{$randomSecondaryAddress}}

  • {{$randomCountry}}

  • {{$randomCountryCode}}

  • {{$randomState}}

  • {{$randomStateAbbr}}

  • {{$randomLatitude}}

  • {{$randomLongitude}}

  • {{$randomColor}}

  • {{$randomDepartment}}

  • {{$randomProductName}}

  • {{$randomPrice}}

  • {{$randomProductAdjective}}

  • {{$randomProductMaterial}}

  • {{$randomProduct}}

  • {{$randomCompanyName}}

  • {{$randomCompanySuffix}}

  • {{$randomCatchPhrase}}

  • {{$randomBs}}

  • {{$randomCatchPhraseAdjective}}

  • {{$randomCatchPhraseDescriptor}}

  • {{$randomCatchPhraseNoun}}

  • {{$randomBsAdjective}}

  • {{$randomBsBuzz}}

  • {{$randomBsNoun}}

  • {{$randomDatabaseColumn}}

  • {{$randomDatabaseType}}

  • {{$randomDatabaseCollation}}

  • {{$randomDatabaseEngine}}

  • {{$randomDatePast}}

  • {{$randomDateFuture}}

  • {{$randomDateBetween}}

  • {{$randomDateRecent}}

  • {{$randomMonth}}

  • {{$randomWeekday}}

  • {{$randomBankAccount}}

  • {{$randomBankAccountName}}

  • {{$randomCreditCardMask}}

  • {{$randomCurrencyAmount}}

  • {{$randomTransactionType}}

  • {{$randomCurrencyCode}}

  • {{$randomCurrencyName}}

  • {{$randomCurrencySymbol}}

  • {{$randomBitcoin}}

  • {{$randomBankAccountIban}}

  • {{$randomBankAccountBic}}

  • {{$randomAbbreviation}}

  • {{$randomAdjective}}

  • {{$randomNoun}}

  • {{$randomVerb}}

  • {{$randomIngverb}}

  • {{$randomPhrase}}

  • {{$randomImage}}

  • {{$randomAvatarImage}}

  • {{$randomImageUrl}}

  • {{$randomAbstractImage}}

  • {{$randomAnimalsImage}}

  • {{$randomBusinessImage}}

  • {{$randomCatsImage}}

  • {{$randomCityImage}}

  • {{$randomFoodImage}}

  • {{$randomNightlifeImage}}

  • {{$randomFashionImage}}

  • {{$randomPeopleImage}}

  • {{$randomNatureImage}}

  • {{$randomSportsImage}}

  • {{$randomTechnicsImage}}

  • {{$randomTransportImage}}

  • {{$randomImageDataUri}}

  • {{$randomEmail}}

  • {{$randomExampleEmail}}

  • {{$randomUserName}}

  • {{$randomProtocol}}

  • {{$randomUrl}}

  • {{$randomDomainName}}

  • {{$randomDomainSuffix}}

  • {{$randomDomainWord}}

  • {{$randomIP}}

  • {{$randomIPV6}}

  • {{$randomUserAgent}}

  • {{$randomHexColor}}

  • {{$randomMACAddress}}

  • {{$randomPassword}}

  • {{$randomLoremWord}}

  • {{$randomLoremWords}}

  • {{$randomLoremSentence}}

  • {{$randomLoremSlug}}

  • {{$randomLoremSentences}}

  • {{$randomLoremParagraph}}

  • {{$randomLoremParagraphs}}

  • {{$randomLoremText}}

  • {{$randomLoremLines}}

  • {{$randomFirstName}}

  • {{$randomLastName}}

  • {{$randomFullName}}

  • {{$randomJobTitle}}

  • {{$randomNamePrefix}}

  • {{$randomNameSuffix}}

  • {{$randomNameTitle}}

  • {{$randomJobDescriptor}}

  • {{$randomJobArea}}

  • {{$randomJobType}}

  • {{$randomPhoneNumber}}

  • {{$randomPhoneNumberFormat}}

  • {{$randomPhoneFormats}}

  • {{$randomArrayElement}}

  • {{$randomObjectElement}}

  • {{$randomUUID}}

  • {{$randomBoolean}}

  • {{$randomWord}}

  • {{$randomWords}}

  • {{$randomLocale}}

  • {{$randomAlphaNumeric}}

  • {{$randomFileName}}

  • {{$randomCommonFileName}}

  • {{$randomMimeType}}

  • {{$randomCommonFileType}}

  • {{$randomCommonFileExt}}

  • {{$randomFileType}}

  • {{$randomFileExt}}

  • {{$randomDirectoryPath}}

  • {{$randomFilePath}}

  • {{$randomSemver}}

还是比较偏英文化,对于中文可能并不太友好,下面来演示一个使用示例:

在请求中使用上面这些变量

监控发送的 HTTP 请求

从上图中可以看到,我们使用到的随机变量在发送请求的时候是已经替换成具体的值的了

编写测试用例

Scripts 介绍

postman 有一套基于 nodejs 的运行时,我们可以写一些 scripts 来在请求发送之前做一些日志等,在得到响应之后测试响应是否与预期一致

postman 的 script 主要分成两类,一类是 Pre-RequestScripts,在发送请求之前执行,一类是 Tests,个人感觉可能叫 Post-ResponseScripts 更好一些,因为我们不仅仅可以写测试,也可以记录日志,也可以设置变量等

上次我们说过了 postman 的测试推荐使用 Collection ,Collection 下可以分目录也可以直接就是 request,目录里也可以有具体的 api request,还可以有子目录

Collection/Folder/Request 都可以定义自己的 Pre-RequestScriptsTests,这些 Scripts 执行顺序如下:

上一级的测试作用于子级所有的请求,也就是说我们可以在 Collection 的 TestScripts 中定义一个测试用例,这会对这个 Collection 下的所有请求都有效,都会验证这个测试是否有效

如果想要实现测试用例的复用可以将类似的请求放在一个目录下针对目录写测试用例,这样这个目录下的请求都会有这个测试用例

如果只是想针对某一个请求的测试,可以针对 request 来写,只在对应 request 的 TestScripts 中定义即可

Scripts 常用语法

Postman Console

postman 是基于 nodejs 的,你可以直接使用 console.log 来记录一些日志,通过 postman console 来查看,在左上角的菜单 View 下有一个 ShowPostmanConsole

我们在请求的 Pre-Scripts 里输出一条日志,然后发送请求

这里的 pm.variables.set("phone","") 是设置 phone 这一参数为空字符串,由下图可以看出,phone 这一变量在发送请求的时候会被替换成空字符串

查看 postman console

可以看到我们在上面输出的日志已经输出到 postman console 了

变量设置

postman 支持的变量分几个层级,

  • global

  • environment

  • collection

  • data(数据文件中的变量值)

  • local

变量优化级:

上面的类型优先级从低到高,“就近原则”

// Variables
// This function searches for the variable across globals and the active environment.
var value = pm.variables.get("variable_key"); // 这个方法会从上面所有的来源寻找对应的变量,就近原则,优先从最靠近自己的地方找
// Globals
// Set a global variable,设置一个全局变量
pm.globals.set("variable_key", "variable_value");
// Get a global variable,从全局变量中获取某个变量的值
pm.globals.get("variable_key");
// Clear a global variable,取消设置全局变量,移除变量
pm.globals.unset("variable_key");
// Environments
// Setting an environment variable, 设置一个环境变量(注,这是postman 中的 <Environment> 环境变量,不同于系统环境变量)
pm.environment.set("variable_key", "variable_value");
// 你也可以序列化一个对象或数组放在变量中
// Setting a nested object as an environment variable
// var array = [1, 2, 3, 4];
// pm.environment.set("array", JSON.stringify(array, null, 2));
// var obj = { a: [1, 2, 3, 4], b: { c: 'val' } };
// pm.environment.set("obj", JSON.stringify(obj));
// Getting an environment variable,从环境中获取某个变量
var value = pm.environment.get("variable_key");
// If the value is a stringified JSON:
// These statements should be wrapped in a try-catch block if the data is coming from an unknown source.
var array = JSON.parse(pm.environment.get("array"));
var obj = JSON.parse(pm.environment.get("obj"));
// // Clear an environment variable, 从环境中移除某一个变量
// pm.environment.unset("variable_key");
// Collection
// Setting an collection variable,设置一个 collection 变量
pm.collectionVariables.set("variable_key", "variableValue");
// Get a collection variable,从 collection 中获取一个变量
var val = pm.collectionVariables.get("variable_key");
// Clear a collection variable,从 collection 中移除一个变量
pm.collectionVariables.unset("variable_key");
// local
pm.variables.set("variable_key", "variable_value");
pm.variables.get("variable_key");

使用变量,如 username => {{username}},使用两层大括号来表示变量引用,比如上面的测试中的 phone

测试用例

postman 的测试用例也是分层级的,上面已经做了简单的介绍,postman 是基于 nodejs 的所以,在nodejs 里可以用的语法大多也都支持,比如 JSON.parse,这里主要介绍几种常用的方法:

// 检查 response 的 statusCode 是 200
pm.test("response is ok", function () {pm.response.to.have.status(200);
});
// 检查响应是 200,并且有 body,body 是一个 json
pm.test("response must be valid and has a json body", function () {// assert that the status code is 200pm.response.to.be.ok; // info, success, redirection, clientError,  serverError, are other variants// assert that the response has a valid JSON bodypm.response.to.be.withBody;pm.response.to.be.json; // this assertion also checks if a body  exists, so the above check is not needed
});
// 定义一个超时时间,检查响应时间是否超时
let responseTimeout = parseInt(pm.variables.get("responseTimeout"));
if(responseTimeout > 0){pm.test(`Response time is less than ${responseTimeout}ms`, function () {pm.expect(pm.response.responseTime).to.be.below(responseTimeout);});   
}
// Convert XML body to a JSON object,使用postman 内置的 xml2Json 将 xml 转换为 json 对象
var jsonObject = xml2Json(responseBody);
//Check for a JSON value
// 检查 json 对象中某一个值是否符合预期
pm.test("Your test name", function () {var jsonData = pm.response.json();pm.expect(jsonData.value).to.eql(100);
});
// 检查数组是否为空
pm.test("Check if array is empty", function () {expect([]).to.be.empty;
});
// 检查字符串是否为空
pm.test("Check if string is empty", function () {pm.expect('').to.be.empty;
});

运行测试:

测试结果会显示出多个测试通过,多少失败的,哪些 assertion 失败,你也可以看到具体的响应信息

使用命令行测试

postman 提供了一个 npm 包 newman,我们可以直接命令行运行测试,也可以在自己的程序里集成 npm 包,在程序里运行

npm install -g newman

使用导出 Collection, 导出之后是一个 json 文件

newman run testCollection.json // 运行 testCollection 测试
newman run testCollection.json -d testData.json // -d 指定数据文件
newman run testCollection.json -d testData.json -r json // -d 指定数据文件,-r 指定 report 类型,默认是 `cli` 直接在命令行中输出测试结果
newman run testCollection.json -r cli,json // -d 指定数据文件,-r 指定 report 类型,默认是 `cli` 直接在命令行中输出测试结果,可以指定多个 reporter,json 会将运行结果保存到 json 文件中
// collection 路径不仅支持本地路径,也支持 url
newman run https://www.getpostman.com/collections/631643-f695cab7-6878-eb55-7943-ad88e1ccfd65-JsLv

示例:

在自己的程序中使用 newman 运行测试

const newman = require('newman'); // require newman in your project
// call newman.run to pass `options` object and wait for callback
newman.run({collection: require('./sample-collection.json'),reporters: 'cli'
}, function (err) {if (err) { throw err; }console.log('collection run complete!');
});

更多用法参考官方文档:https://github.com/postmanlabs/newman#using-newman-cli

Reference

  • https://learning.getpostman.com/docs/postman/variables-and-environments/variables-list/

  • https://learning.getpostman.com/docs/postman/scripts/intro-to-scripts/

  • https://learning.getpostman.com/docs/postman/scripts/test-examples/

  • https://github.com/postmanlabs/newman

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/312464.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

图 无向图 有向图

若无向图G &#xff08;V&#xff0c;E&#xff09;中含7个顶点&#xff0c;要保证图G在任何情况下都是连通的&#xff0c;则需要的边数最少是&#xff1a; A.6 B.15 C.16 D.21 (n-1)*(n-2)/21 6 * 5/2116 设无向图的顶点个数为N&#xff0c;则该图最多有多少条边&#xff1f;…

Excel催化剂回顾2019年产出(文章合集),展望2020年

一年结束&#xff0c;大家都对自己一年辛勤耕耘作一个总结&#xff0c;Excel催化剂也不落俗&#xff0c;也来一篇文章合集式的梳理&#xff0c;方便大家对Excel催化剂的产出有一个宏观全局的认识。不断创新中前行Excel催化剂从2018年开波以来&#xff0c;累计到如今已有114个大…

朗文3000词汇表带音标_英语零基础音标语法都不会词汇量3000 学雅思到6/6.5分 需要多久 该如何做?...

谢邀~题主好&#xff01;看来题主的零基础非常纯正。你现在测试的单词量是3000&#xff0c;只能大概展示出你的一些基础&#xff0c;但其实真正的还是要看你会使用&#xff0c;真正理解用法、语境的词汇有多少&#xff0c;而不是为了看起来有多少的那个数字。那么首先题主最好的…

选择排序 插入排序 交换排序

动图演示&#xff1a; https://www.runoob.com/w3cnote/bubble-sort.html 选择排序 简单选择排序 在未排序的序列中&#xff0c;选出最小的元素和序列的首位元素交换&#xff0c;接下来在剩下的未排序序列中&#xff0c;再选出最小元素与序列的第二位元素交换&#xff0c;以此…

ASP.NETCore编程实现基本认证

HTTP基本认证在HTTP中&#xff0c;HTTP基本认证&#xff08;Basic Authentication&#xff09;是一种允许浏览器或其他客户端程序使用&#xff08;用户名&#xff0c;口令&#xff09;请求资源的身份验证方式&#xff0c;不要求cookie,session identifier、login page等标记或载…

计算机原理(计算机系统漫游)

计算机五大组成部件&#xff1a;运算器&#xff08;ALU&#xff09;&#xff0c;控制器&#xff0c;存储器&#xff0c;输入部件&#xff0c;输出部件 1.控制器 2.运算器 逻辑运算&#xff08;判断事物的对与错&#xff09; 数学运算(11) 控制器运算器中央处理器&#xff08;CP…

使用ASP.NET Core 3.x 构建 RESTful API - 4.2 过滤和搜索

向Web API传递参数数据可以通过多种方式来传给API。 Binding Source Attributes 会告诉 Model 的绑定引擎从哪里找到绑定源。 共有以下六种 Binding Source Attributes&#xff1a; [FromBody] 请求的 Body [FromForm] 请求的 Body 中的 form数据 [FromHeader] 请求的 Header […

360浏览器linux版本_360安全浏览器崩溃解决方案

360安全浏览器崩溃解决方案方案一&#xff1a;打开360安全浏览器&#xff0c;按键盘上的F1调出浏览器医生界面&#xff0c;点击一键修复即可。如图所示&#xff1a;方案二&#xff1a;360浏览器打开了太多标签占用内存&#xff0c;并且随着浏览器开着的时间越长&#xff0c;占用…

.NET 开源软件开发BIM工具包xBIM

一、xBIM 简介BIM&#xff08;Building Information Modelling&#xff09;建筑信息模型&#xff0c;xBIM&#xff08;eXtensible Building Information Modelling&#xff09;可扩展的建筑信息模型。它是一个.NET 开源软件开发BIM工具包&#xff0c;支持BuildingSmart数据模型…

< meta name=“viewport“ content=“width=device-width, initial-scale=1.0“>的解释

< meta name“viewport” content“widthdevice-width, initial-scale1.0”> meta是html语言head区的一个辅助性标签&#xff0c;位于文档的头部&#xff0c;不包含任何内容 标签的属性定义了与文档相关的名称/值对 meta元素可提供相关页面的元信息&#xff0c;比如针对…

<meta name=“robots“ content=“index,follow“>的解释

为了让搜索引擎禁止抓取本页面 此标签必须放在< head >和< /head >之间 content中的值决定允许抓取的类型&#xff0c;必须同时包含两个值&#xff1a;是否允许索引&#xff08;index&#xff09;和是否跟踪链接&#xff08;follow&#xff0c;也可以理解为是否允…

2019(dotNet全栈开发)公众号回顾

2019年已经过去&#xff0c;人口红利已经逐渐消失&#xff0c;也许这是这10年互联网史上最糟糕的一年&#xff0c;也可能这是未来10年互联网史上最好的一年关于公众号&#xff0c;我其实很早就开始注册了&#xff0c;只是一直没怎么运营&#xff08;ps&#xff1a;不知道怎么推…

CSS padding margin border属性讲解

把所有网页上的对象都放在一个盒&#xff08;box&#xff09;中 &#xff0c;设计师可以通过创建定义来控制这个盒的属性&#xff0c;这些对象包括段落、列表、标题、图片以及层。 盒模型主要定义四个区域&#xff1a; 内容&#xff08;content&#xff09; 内边距&#xff08;…

laravel 模板继承_Laravel框架模板之公共模板、继承、包含实现方法分析

本文主要介绍了laravel框架模板之公共模板、继承、包含实现方法,结合实例形式分析了Laravel框架中公共模板的建立、模板包含、模板继承等相关操作技巧&#xff0c;需要的朋友可以参考下&#xff0c;具体如下&#xff1a;简介&#xff1a;利用laravel框架开发后台管理系统或web站…

css表格表单属性

表格标签 table表格 属性&#xff1a; border 边框属性 值 数字 width 宽度 值 数字 height 高度 值 数字 cellpadding单元格的内容到单元格边的距离 cellspacing单元格和单元格之间的间距 align规定表格水平如何摆放 值 left/center/right tr行 属性&#xff1a; height 高度…

2019 amazingdotnet 公众号回顾

2019 精彩文章汇总Intro新的一年了&#xff0c;把去年的精彩文章汇总一下&#xff0c;希望能对大家有所帮助博客园推荐文章asp.net core 3.0 更新简记asp.net core 从单机到集群动手造轮子&#xff1a;实现一个简单的 EventBusasp.net core 3.0 中使用 swaggerasp.net core 自定…

echarts字变大_在echarts中如何调整lable的字体大小?

波斯汪series[i]-pie.data[i].label.normal.textStyle.fontSize透過設定 fontSize 就可以調整大小了, 你可以參考 官網的範例, 手動修改左側欄 label 的 fontSize 看看, 是可以調整大小的.文檔在此用 legend.textStyle.fontSize 更改示例大小用 itemStyle.normal.label.textSty…

Identifiers in Java(Java标识符)

Identifiers&#xff08;标识符&#xff09; in Java are symbolic(符号化) names used for identification. They can be a class name, variable name, method name, package name, constant&#xff08;常量&#xff09; name, and more. However, In Java, There are some …

【实战 Ids4】║ 客户端、服务端、授权中心全线打通!

1、经过元旦两天的全力整改&#xff0c;终于在这新的一年&#xff0c;完成了我的布道生涯的第一个大步走 —— 那就是客户端&#xff08;VUE&#xff09;、服务端&#xff08;ASP.NET Core API&#xff09;、授权中心&#xff08;IdentityServer4&#xff09;的大融合&#xff…

补丁 检测系统_大云制造 | BCLinux For ARM64 V7.6操作系统正式发布

友情提示&#xff1a;全文3000多文字&#xff0c;预计阅读时间10分钟概述大云企业操作系统(BC-Linux&#xff0c;BigCloud Enterprise Linux)是中移(苏州)软件技术有限公司借助开源社区优势&#xff0c;通过定制化手段研发的高性能、安全可靠、自主可控的企业级Linux操作系统。…