如何在Jmeter中用一些随机数替换变量的字符

How to replace the characters of a variable with some random numbers in Jmeter

我正在尝试从 Debug Sampler 中获取一个变量,并将变量的字符替换为一些随机生成的数字。我添加了一个 BeanShell 采样器来编写自定义代码。下面是一段代码:

String myvariable = vars.get("Corr_ContextN");
chars1 = new ArrayList();
chars2 = new ArrayList();

for(int i =0; i<myvariable.length(); i++) {
chars1.add(myvariable.charAt(i)); }

String value = chars1.toString();

Random randomnumber = new Random();
for (int idx=1; idx < 15; ++idx) {
chars2.add(randomnumber.nextInt(100)); }

String Newvalue1 = chars2.toString();
vars.put("NewVariable", Newvalue1 );

通过上述方式,我在调试采样器 (NewVariable) 中获得了一个带有随机数列表的新变量。但是我想用创建的这个 NewVariable 替换现有变量 "Corr_ContextN" 。换句话说,现有变量应该替换为一些动态生成的 number/variable.

请帮帮我。

只需将最后一行更改为:

vars.put("Corr_ContextN", Newvalue1 );

P.S。考虑使用 JSR223 Sampler 而不是 Beanshell。您甚至可以重复使用相同的代码,这些代码在被 Groovy 引擎编译时性能会更好。


P.P.S。请注意,使用 __Random function which is capable of storing randomly generated numbers into JMeter Variables as well as returning them in place where the function is called. Check out How to Use JMeter Functions post 系列学习 JMeter 中的函数, 会容易得多。