我需要在邮递员中创建一个预请求脚本,以在值数组中使用随机元素设置环境变量。有谁有想法?
编辑:(已解决)
<!-- language: lang-js -->
var order_id = ["one","two","three","four","five"];
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
pm.environment.set("order_id", order_id[getRandomInt(0,4)]);
Postman有许多内置模块,允许您执行此类操作,而无需以这种方式编写本机JS代码。
删除该函数,只需添加它,它将使用Lodash random()
函数执行相同的操作:
var order_id = ["one","two","three","four","five"]
pm.environment.set("order_id", order_id[_.random(0,4)]
)
或者只使用Lodash shuffle
功能:
var order_id = ["one","two","three","four","five"]
pm.environment.set("order_id", _.shuffle(order_id)[0])