如何在环境变量中设置数值

Sam*_*Sam 4 postman

问题:我想在环境变量中设置一个计数器变量(一个数值),因此在“测试”中我们可以控制流程。

我的实验: 我编写了一个简单的API调用,其中包含以下内容:

  1. 规定设置计数器变量-

postman.setEnvironmentVariable(“ mycounter”,1);

  1. 测试验证计数器变量,如果其值等于1,则将其递增-

如果(postman.getEnvironmentVariable(“ mycounter”)== 1){

postman.setEnvironmentVariable("result", "YES");
postman.setEnvironmentVariable("mycounter", 1+postman.getEnvironmentVariable("mycounter")); 
Run Code Online (Sandbox Code Playgroud)

} else {postman.setEnvironmentVariable(“ result”,“ NO”); }

但是当我检查“ mycounter”的值时

  • 实际值:11
  • 期望值:2

有人可以指出如何在环境变量中设置数值吗?

Sam*_*Sam 11

我有解决方法。通过使用Number函数将字符串转换为整数。

所以

if (postman.getEnvironmentVariable("mycounter") == 1 ) {
    postman.setEnvironmentVariable("result", "YES");
    postman.setEnvironmentVariable("mycounter", 1+Number(postman.getEnvironmentVariable("mycounter")));  
} else {
    postman.setEnvironmentVariable("result", "NO"); 
}
Run Code Online (Sandbox Code Playgroud)


mrr*_*aat 5

我认为萨姆的答案有效,但这是我在一个预请求脚本中使用的一种更干净的方法

let myCounter = +environment["mycounter"];  // '+' Convert String into Integer
if (myCounter == 1) {
    myCounter++;
    postman.setEnvironmentVariable("result", "YES");
    postman.setEnvironmentVariable("mycounter", myCounter);  
} else {
    postman.setEnvironmentVariable("result", "NO"); 
}
Run Code Online (Sandbox Code Playgroud)

有关转换的更多信息==> /sf/answers/79367011/