在 Postman 中重用 {{$randomInt}}Postman、randomInt

2023-09-07 11:03:17 作者:花未开欲以败丶

我的第一个请求是:GET http://example.com?int={{$randomInt}}.我需要将第二个请求(其中包含其他测试)运行到相同的地址,所以我需要保存生成的变量.我该怎么做?

My 1st request is: GET http://example.com?int={{$randomInt}}. I need to run 2nd request (with other tests in it) to the same address, so I need to save generated variable. How can I do it?

我在第一次请求后在测试"沙箱中尝试 pm.variables.get("int"),但此代码看不到 int var.

I was trying pm.variables.get("int") in the "Tests" sandbox after 1st request, but this code cannot see int var.

在 Pre-req 中创建随机数.沙箱到第一个请求:postman.setGlobalVariable('int', Math.floor(Math.random() * 1000));也无济于事,因为我需要在 URL 中使用这个参数,而Pre-req."块在请求之后但在测试之前运行.

Creating random number in Pre-req. sandbox to 1st request: postman.setGlobalVariable('int', Math.floor(Math.random() * 1000)); doesn't help either, because I need to use this param in the URL, while "Pre-req." block is run after request but before tests.

那么如何在第一个请求之前生成随机变量并将其存储以在第二个请求中使用?

So how can I generate random var before 1st request and store it to use in 2nd request?

推荐答案

如果在第一个请求的Pre-Request Script中设置:

If you set this in the Pre-Request Script of the first request:

pm.globals.set('int', Math.floor(Math.random() * 1000))

Or

// Using the built-in Lodash module
pm.globals.set("int", _.random(0, 1000))

您将能够引用它并在任何请求中使用 {{int}} 语法.如果您在第一个请求中添加此值,然后在 URL http://first-example.com?int={{int}} 中使用它,则此值将保持不变,您可以再次使用它在第二个请求中 http://second-example.com?int={{int}}

You will be able to reference it and use the {{int}} syntax in any request. If you add this in the first request and then use it in the URL http://first-example.com?int={{int}} this value will then persist and you can use it again in a second request http://second-example.com?int={{int}}

每次使用 {{$randomInt}} 时,都会在运行时生成一个新值.

Each time that {{$randomInt}} is used, it will generate a new value at run time.