2014-01-28 74 views
50

我正在使用Postman的打包应用程序版本来针对我的Rest API编写测试。我试图在连续测试之间管理状态。为了解决这个问题,暴露于Javascript测试运行时的Postman对象具有设置变量的方法,但没有用于读取的方法。如何在Postman测试中读取环境变量?

postman.setEnvironmentVariable("key", value); 

现在,我可以在下次调用时通过{{key}}结构读取该值,该结构从当前环境吸取值。但是,这在测试中不起作用;它只适用于请求建立的东西。

那么,有没有从测试中读这些东西呢?

回答

75

按照文档here可以使用

environment["foo"] OR environment.foo 
globals["bar"] OR globals.bar 

访问它们。

ie;

postman.setEnvironmentVariable("foo", "bar"); 

tests["environment var foo = bar"] = environment.foo === "bar"; 

postman.setGlobalVariable("foobar", "1"); 

tests["global var foobar = true"] = globals.foobar == true; 

postman.setGlobalVariable("bar", "0"); 

tests["global var bar = false"] = globals.bar == false; 
+3

我注意到的一件事是,当我设置全局变量时,我将它设置为int;当我读回来时,它是一个字符串。所以我需要解析它:tests [“stress”] = data.Rating.RatingScoreList [1] .Value === parseInt(globals.stress); – Duncan

+8

从文档[这里](https://www.getpostman.com/docs/environments):“警告 - 环境和全局变量将始终以字符串形式存储。如果您要存储对象/数组,请务必使用JSON .stringify()它们在存储之前,而JSON.parse()它们在检索时。“ – GrayedFox

+0

另请注意,如果您计划使用[邮递员监视器](https://www.getpostman.com/docs/v6/postman/monitors/intro_monitors),而环境变量则不支持全局变量。 –

1

邮差更新了他们的沙盒,并增加了pm.* API。虽然在测试脚本中读取变量较旧的语法仍然有效,根据docs

一旦一个变量被设置,使用pm.variables.get()方法,或者 或者,使pm.environment.get()pm.global.get() 方法取决于取出变量的适当范围。 方法需要使用变量名称作为参数来检索脚本中存储的值。