我有一个CSV文件,其中包含我使用Bean Shell脚本读取的数据并基于该数据填充ArrayList。以下是其代码。
//Populate Beanshell script
import java.text.*;
import java.io.*;
import java.util.*;
ArrayList strList = new ArrayList();
try {
File file = new File("path/to/csv");
if (!file.exists()) {
throw new Exception ("ERROR: file not found");
}
BufferedReader bufRdr = new BufferedReader(new FileReader(file));
String line = null;
while((line = bufRdr.readLine()) != null) {
strList.add(line);
}
bufRdr.close();
}
catch (Exception ex) {
IsSuccess = false;
log.error(ex.getMessage());
System.err.println(ex.getMessage());
}
catch (Throwable thex) {
System.err.println(thex.getMessage());
}
现在我想以随机的方式利用这些数据,所以我试图使用类似的东西
//Consumer bean shell script
//Not able to access strList since vars.put cannot store an object
Random rnd = new java.util.Random();
vars.put("TheValue",strList.get(rnd.nextInt(strList.size())));
但是我无法执行此操作,因为在vars.put中,我无法存储数组或列表,只能存储基本类型。因此,无法从另一个BeanShell脚本访问填充函数的ArrayList。
在这种情况下,如何实现随机化,因为从性能的角度来看,每次都调用填充函数是不好的。
最佳答案
我建议使用bsh.shared命名空间,这样,您将可以存储任何Java对象,并根据需要甚至从不同的线程组访问它。
特定于JMeter的示例在官方文档的Sharing Variables章中
在第一个脚本的结尾:
bsh.shared.strList = strList;
在第二个脚本的开头:
List strList = bsh.shared.strList;
Random rnd = new java.util.Random();
vars.put("TheValue",strList.get(rnd.nextInt(strList.size())));
有关JMeter的Beanshell脚本的更多详细信息,请参见How to use BeanShell: JMeter's favorite built-in component指南。