postman接口自动化(三)变量设置与使用

本文介绍了Postman中的环境变量和变量设置,包括环境变量的概念、如何设置和切换环境,以及变量的类型如局部变量、数据文件变量、环境变量、Collection变量和全局变量。讲解了变量的优先级,并展示了如何在请求和代码中使用变量,同时提到了Postman的内置动态变量用于生成随机数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、环境变量
环境是由一组键值对形式的环境变量构成的变量组合。
在做接口测试的时候,通常需要在本地调试,或者需要在开发环境、测试环境及开发环境运行,不同的环境的域名(host)、数据库配置等设置不同。
通过配置不同的环境变量值,再在请求中使用不同的值,那么可以通过切换环境来切换不同的值,以达到不用修改任何请求就能在任意环境运行。
在这里插入图片描述
在打开的窗口中设置好环境名称和变量值即可:
**VARIABLE:**设置一个环境变量名称标识,通过变量名调用该变量;
INITIAL VALUE:共享 Collection 用到的值,如果不共享 Collection 可以不用设置;
**CURRENT VALUE:**当前值,用于当前 Postman 运行请求时使用的值,一般我们设置这个值;
···:这里的···按钮可以设置列的显示;
Presist All:将所有当前表格中 initial 列的共享值设置为 当前值;
Reset All:将所有当前表格中 当前值设置为 initial 列的共享值。

环境切换:
点击右上角齿轮旁边的下拉菜单可以切换环境:
在这里插入图片描述
切换环境后,环境变量会随着改变。
可以通过右上角的眼睛?按钮查看当前环境所有环境变量的值和全局变量的值

分享环境变量
点击右上角的齿轮打开环境编辑界面:在这里插入图片描述
分享环境有两种方式,一种是点击 Share 按钮,但是这种方式需要付费才行。
第二种方式是上图中标记的位置,以 Json 文件的方式导出环境配置。
将 Json 文件分享给团队成员,其他成员通过 Postman 顶部的 Import 按钮导入环境即可。

二、变量设置
变量是用来存储动态值的静态标识符。变量标识的信息可以更改,但是对变量的操作保持不变。
我们可以在多个位置重用变量值。如果变量的值发生变化,变量的每个实例都会相应的更改,从而减少了重复修改的需要和出错的可能性。
我们还可以通过变量从一个请求中获取数据,在另一个请求中使用它们。

在 Postman 中有以下几种变量:
● 局部变量 local
data 文件中的变量 data
● 环境变量 environment
Collection 中的变量 collection
● 全局变量 global
● 内置变量 dynamic

除局部变量以外的其他变量值只能是字符串,如果要存储对象或者其他数据类型的数据,需要先转换为字符串(JSON.stringify()),然后在使用时转换回去(JSON.parse())。

变量优先级
以下的图可以说明变量的优先级,越外层的变量优先级越低。

比如同一个变量名 host,在 environment 和 global 中分别设置了不同的值,那么最终运行请求的时候,实际使用的是 environment 中的值,因为 environment 变量的优先级比 global 更高。
在这里插入图片描述
设置变量
1、局部变量 local variable
局部变量是在代码(Pre-request,Tests)中设置的。使用 JavaScript 的变量语法即可。
在这里插入图片描述
其优先级最高,但是仅在当前的脚本环境中有效,对于上图中的json变量,只在当前请求的 Tests 中的脚本有效。

2、data 文件中的变量 data
在 Collection 运行中我们讲过可以加载数据驱动的文件(CSV,JSON)中的值。
在这里插入图片描述
上图中通过加载的数据文件中读取出的一个变量msisdn

3、环境变量 environment
环境变量可以通过两种方式设置,一种是在环境设置中进行设置:
另一种设置环境变量的方法是,在代码(Pre-request,Tests)中设置。
在这里插入图片描述
上图中通过代码设置了一个变量 ip,其值为 192.168.75.29。

4、Collection 中的变量 collection
在 Collection 中可以设置变量,设置的方法是在 Collection 编辑界面的 Variables选项卡中:
在这里插入图片描述
在这里插入图片描述
上图中设置了一个 Collection 变量 ip,其值为192.168.75.29。
也可以看到这里的设置界面很类似环境变量的设置。

5、全局变量 global
全局变量的设置类似环境变量的设置,也有两种方式。
一种方法,那就是通过代码(Pre-request,Tests)设置。
在这里插入图片描述
上图中通过代码设置了一个全局变量 msisdn, 其值为13828789407。
另一种方法是在环境设置(就是设置环境变量那个地方)界面进行设置:
在这里插入图片描述

三、内置变量
内置变量dynamic variables是由 Postman 提供的大量预设变量,用来生成一些随机值,方便测试过程中通过一些重复性校验。
在构造请求的时候,输入{,就会出现这些预设变量的待选项:
在这里插入图片描述

Postman 提供了非常多类型的随机生成的内容,可以在测试的时候省去很多构造数据的过程。
由于这些变量如此众多,不用看完,需要的时候再来查阅即可。最重要的内容是随机生成唯一性的字符串变量。

随机唯一性字符串
这些是唯一性很强的字符串,对于一些有唯一限制的内容可以使用这些值来填充。

Variable NameDescriptionExamples
$guiduuid-v4 风格的 guid,随机性非常强“611c2e81-2ccb-42d8-9ddc-2d0bfa65c1b4”
$timestamp时间戳1562757107 , 1562757108 , 1562757109
$randomUUID随机 36 位的 UUID“6929bb52-3ab2-448a-9796-d6480ecad36b”
随机文字、字符串、颜色(码)
Variable NameDescriptionExamples
$randomAlphaNumeric1位随机字符或数字6 , “y” , “z”
$randomBoolean随机布尔值 (true/false)true , false , false , true
$randomInt1~1000 之间的随机整数802 , 494 , 200
$randomColor随机颜色单词“red” , “fuchsia” , “grey”
$randomHexColor随机颜色码“#47594a” , “#431e48” , “#106f21”
$randomAbbreviation随机缩写SQL , PCI , JSON
随机网络标识和 IP 地址
Variable NameDescriptionExamples
$randomIP随机的 IPv4 地址241.102.234.100 , 216.7.27.38
$randomIPV6随机 IPv6 地址dbe2:7ae6:119b:c161:1560:6dda:3a9b:90a9
$randomMACAddress随机 MAC(物理)地址33:d4:68:5f:b4:c7 , 1f:6e:db:3d:ed:fa
$randomPassword由字母和数字组成的 15 位随机密码t9iXe7COoDKv8k3 , QAzNFQtvR9cg2rq
$randomLocale随机两位字母组成的语言代码 (ISO 639-1)“ny” , “sr” , “si”
$randomUserAgent随机用户代理Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.9.8; rv:15.6) Gecko/20100101 Firefox/15.6.6
$randomProtocol随机协议类型“http” , “https”
$randomSemver由数字组成的随机版本号7.0.5 , 2.5.8 , 6.4.9
随机姓名(英文)
Variable NameDescriptionExamples
$randomFirstName随机的名字(英文)Ethan , Chandler , Megane
$randomLastName随机姓氏(英文)Schaden , Schneider , Willms
$randomFullName随机全名(名字 姓氏)Connie Runolfsdottir , Sylvan Fay , Jonathon Kunze
$randomNamePrefix随机称呼Dr. , Ms. , Mr.
$randomNameSuffix随机姓名后缀I , MD , DDS
职业
Variable NameDescriptionExamples
$randomJobArea随机工作范围Mobility , Intranet , Configuration
$randomJobDescriptor随机职业等级Forward , Corporate , Senior
$randomJobTitle随机工作标题International Creative Liaison ,
$randomJobType随机工作类型Supervisor , Manager , Coordinator
随机电话号码、区域、地址
Variable NameDescriptionExamples
$randomPhoneNumber随机 10 位数字电话号码700-008-5275 , 494-261-3424 , 662-302-7817
$randomPhoneNumberExt随机扩展号码(包含区号)27-199-983-3864 , 99-841-448-2775
$randomCity随机城市名称Spinkahaven , Korbinburgh , Lefflerport
$randomStreetName随机街道名称Kuhic Island , General Street , Kendrick Springs
$randomStreetAddress随机街道地址5742 Harvey Streets , 47906 Wilmer Orchard
$randomCountry随机国家名称Lao People’s Democratic Republic , Kazakhstan , Austria
$randomCountryCode随机两位字符的国家编码 (ISO 3166-1 alpha-2)CV , MD , TD
$randomLatitude随机纬度55.2099 , 27.3644 , -84.7514
$randomLongitude随机精度40.6609 , 171.7139 , -159.9757
随机图片
Variable NameDescription
$randomImage随机图片地址
$randomAvatarImage随机头像图片
$randomImageUrl随机图片地址
$randomAbstractImage随机头像缩略图
$randomAnimalsImage随机动物图片地址
$randomBusinessImage随机股票业务图片
$randomCatsImage随机猫图片
$randomCityImage随机城市图片
$randomFoodImage随机食物图片
$randomNightlifeImage随机夜生活图片
$randomFashionImage随机时尚图片
$randomPeopleImage随机人物图片
$randomNatureImage随机自然风景图片
$randomSportsImage随机运动图片
$randomTechnicsImage随机科技图片
$randomTransportImage随机交通工具图片
$randomImageDataUri随机图片的 data 数据

随机金融类数据

Variable NameDecriptionExamples
$randomBankAccount随机的8位数字银行帐号09454073 , 65653440 , 75728757
$randomBankAccountName随机的银行帐户名称(e.g. savings account, checking account)Home Loan Account , Checking Account , Auto Loan Account
$randomCreditCardMask随机屏蔽的信用卡号3622 , 5815 , 6257
$randomBankAccountBic随机银行识别码 (Bank Identifier Code)EZIAUGJ1 , KXCUTVJ1 , DIVIPLL1
$randomBankAccountIban随机 15-31位的国际银行帐号 (International Bank Account Number)MU20ZPUN3039684000618086155TKZ
$randomTransactionType随机交易类型 (e.g. invoice, payment, deposit)invoice , payment , deposit
$randomCurrencyCode随机的 3 位字母的货币代码 (ISO-4217)CDF , ZMK , GNF
$randomCurrencyName随机货币名称CFP Franc , Cordoba Oro , Pound Sterling
$randomCurrencySymbol随机货币标志$ , £
$randomBitcoin随机比特币地址3VB8JGT7Y4Z63U68KGGKDXMLLH5
随机商业数据
Variable NameDecriptionExamples
$randomCompanyName随机公司名称Johns - Kassulke , Grady LLC
$randomCompanySuffix随机公司后缀(e.g. Inc, LLC, Group)Inc , LLC , Group
$randomBs随机商业用语killer leverage schemas ,
$randomBsAdjective随机商业形容词用语viral , 24/7 , 24/365
$randomBsBuzz随机商业流行词repurpose , harness , transition
$randomBsNoun随机商业名词e-services , markets , interfaces
随机警句(标语)
Variable NameDecriptionExamples
$randomCatchPhrase随机名言警句Future-proofed heuristic open architecture ,
$randomCatchPhraseAdjective随机流行语形容词Self-enabling , Business-focused , Down-sized
$randomCatchPhraseDescriptor随机流行描述符号bandwidth-monitored , needs-based , homogeneous
$randomCatchPhraseNoun随机生成给一个流行名词secured line , superstructure , installation
随机数据库相关数据
Variable NameDecriptionExamples
$randomDatabaseColumn随机数据库列名updatedAt , token , group
$randomDatabaseType随机数据库类型tinyint , text
$randomDatabaseCollation随机数据库排序规则cp1250_bin , utf8_general_ci , cp1250_general_ci
$randomDatabaseEngine随机数据库引擎MyISAM , InnoDB , Memory

随机日期

Variable NameDecriptionExamples
$randomDateFuture随机未来时间Tue Mar 17 2020 13:11:50 GMT+0530 (India Standard Time) ,
$randomDatePast随机过去时间Sat Mar 02 2019 09:09:26 GMT+0530 (India Standard Time) ,
$randomDateRecent随机近期时间Tue Jul 09 2019 23:12:37 GMT+0530 (India Standard Time) ,
$randomWeekday随机星期几Thursday , Friday , Monday
$randomMonth随机月份February , May , January
随机域名、电子邮件和用户名
Variable NameDecriptionExamples
$randomDomainName随机完整域名gracie.biz , armando.biz , trevor.info
$randomDomainSuffix随机顶级域名org , net , com
$randomDomainWord随机不合法域名gwen , jaden , donnell
$randomEmail随机电子邮箱地址Pablo62@gmail.com , Ruthe42@hotmail.com , Iva.Kovacek61@hotmail.com
$randomExampleEmail随机电子邮箱地址,域名为exampleTalon28@example.com , Quinten_Kerluke45@example.net , Casey81@example.net
$randomUserName随机用户名Jarrell.Gutkowski , Lottie.Smitham24 , Alia99
$randomUrl随机 URL 地址https://anais.net , https://tristin.net , http://jakob.name
随机文件名和目录
Variable NameDecriptionExamples
$randomFileName随机文件名 (包括不常用的扩展名)neural_sri_lanka_rupee_gloves.gdoc ,
$randomFileType随机文件类型 (包括不常用的文件类型)model , application , video
$randomFileExt随机文件扩展名 (包括不常见的文件扩展名)war , book , fsc
$randomCommonFileName随机文件名well_modulated.mpg4 ,
$randomCommonFileType随机常见文件类型application , audio
$randomCommonFileExt随机常见文件扩展名m2v , wav , png
$randomFilePath随机文件路径/home/programming_chicken.cpio ,
$randomDirectoryPath随机目录路径/usr/bin , /root , /usr/local/bin
$randomMimeType随机 MIME 类型(header 中的 content-type 会用到)audio/vnd.vmx.cvsd ,
随机物料(库存、商品等)
Variable NameDecriptionExamples
$randomPrice随机生成 100.00 ~ 999.00 之间的价格531.55 , 488.76 , 511.56
$randomProduct随机商品Towels , Pizza , Pants
$randomProductAdjective随机商品形容词Unbranded , Incredible , Tasty
$randomProductMaterial随机商品材料Steel , Plastic , Frozen
$randomProductName随机商品名称Handmade Concrete Tuna , Refined Rubber Hat
$randomDepartment随机商业分类Tools , Movies , Electronics
基于英语语法的随机数据
Variable NameDecriptionExamples
$randomNoun随机名词matrix , bus , bandwidth
$randomVerb随机动词parse , quantify , navigate
$randomIngverb随机带 “-ing” 的动词synthesizing , navigating , backing up
$randomAdjective随机形容词auxiliary , multi-byte , back-end
$randomWord随机单词withdrawal , infrastructures , IB
$randomWords一些随机单词构成的字符串Samoa Synergistic sticky copying Grocery ,
$randomPhrase随机短语You can’t program the monitor without navigating the mobile XML program! ,
随机的文本内容
Variable NameDecriptionExamples
$randomLoremWord随机单词est
$randomLoremWords随机单词构成的短语vel repellat nobis
$randomLoremSentence随机单词构成的句子Molestias consequuntur nisi non quod.
$randomLoremSentences随机 2~6 条句子构成的段落Et sint voluptas similique iure amet perspiciatis vero sequi atque. Ut porro sit et hic. Neque aspernatur vitae fugiat ut dolore et veritatis. Ab iusto ex delectus animi. Voluptates nisi iusto. Impedit quod quae voluptate qui.
$randomLoremParagraph随机单词构成的一段话Ab aliquid odio iste quo voluptas voluptatem dignissimos velit. Recusandae facilis qui commodi ea magnam enim nostrum quia quis. Nihil est suscipit assumenda ut voluptatem sed. Esse ab voluptas odit qui molestiae. Rem est nesciunt est quis ipsam expedita consequuntur.
$randomLoremParagraphs随机单词构成的 3 个段落Voluptatem rem magnam aliquam ab id aut quaerat. Placeat provident possimus voluptatibus dicta velit non aut quasi. Mollitia et aliquam expedita sunt dolores nam consequuntur. Nam dolorum delectus ipsam repudiandae et ipsam ut voluptatum totam. Nobis labore labore recusandae ipsam quo.
$randomLoremText随机单词构成的文本Quisquam asperiores exercitationem ut ipsum. Aut eius nesciunt. Et reiciendis aut alias eaque. Nihil amet laboriosam pariatur eligendi. Sunt ullam ut sint natus ducimus. Voluptas harum aspernatur soluta rem nam.
$randomLoremSlug随机单词构成的 URL 部分eos-aperiam-accusamus , beatae-id-molestiae , qui-est-repellat
$randomLoremLines由随机单词构成的 1~5 行数据(用回车符分隔)Ducimus in ut mollitia.\nA itaque non.\nHarum temporibus nihil voluptas.\nIste in sed et

四、变量的使用
首先变量要遵循我们前面提到的优先级:

局部变量 local > data 文件中的变量 data > 环境变量 environment > Collection 中的变量
collection > 全局变量 global

优先级是针对不同级别的变量中都设置了相同的变量名的情况,在使用时才会有优先级之分,如果每个环境的变量名不同,那么也不会互相影响。
只是说在遇到变量时,找变量的过程是从局部到全局的顺序,在某一级找到对应的变量名,就会使用哪一级的变量。
使用变量有两种方式,一种是在请求中使用,另一种是在代码(Pre-request Script 和 Tests)中使用。

在请求中使用

在请求中使用变量 variable,使用两对大括号标识{{变量名}}。
以下是变量设置、变量使用及实际运行时的变量取值的综合图:
在这里插入图片描述

图片说明: 上图中设置了一个名为 test 的环境,其中有三个变量,分别是host,path,value; 新建了一个请求,名为POST
Form Data的请求,其中 URL 使用了host和path两个变量,body 中使用了value变量;
最后运行请求后,三个变量都由环境中设置的值替换。

在代码(Pre-request Script 和 Tests)中使用变量
在代码中调用变量,需要使用 Postman 预设的代码pm.environment.get(“变量名”),以上面的请求和变量为例:
在这里插入图片描述

var v = pm.environment.get("value"); // 获取环境变量 value 的值并存在局部变量 v 中
console.log('value变量的值为:', value)  // 打印变量值

环境变量和全局变量必须使用预设的代码获取:
环境变量:pm.environment.get(“变量名”)
全局变量:pm.globals.get(“变量名”)
上述代码都可以从 Tests 右侧的预设代码中获取:
在这里插入图片描述
还有一种变量在 Tests 中使用也需要通过代码获取,那就是通过数据文件传递的 Data 变量,其使用的预设代码为:

pm.iterationData.get("变量名")

内置变量使用
Postman 中有很多内置变量,用来生成随机数据。这些内置变量只能用于请求中的 URL / headers / body 中使用,不能在代码中使用。
在请求中使用:
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值