在 Postman 中重用 {{$randomInt}}

Shu*_*rov 4 postman postman-collection-runner

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

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

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

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

Dan*_*ton 13

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

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

Or

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

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

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