我已使用下面的 BeanShell 将用户定义的变量声明为“projectHome”,该变量返回 jmx 文件的绝对路径。
${__BeanShell(import org.apache.jmeter.services.FileServer; FileServer.getFileServer().getBaseDir();)}
在 Windows 上返回:projectHome=C:\Users\dd\Desktop\API_Testing
在 MacOS 上它返回: projectHome=/Users/dd/Desktop/API_Testing
变量值在 MacOS 上的以下 BeanShell Sampler 中工作正常:
import java.io.FileWriter;
import java.util.Arrays;
import java.io.Writer;
import java.util.List;
//Default separator
char SEPARATOR = ',';
//function write line in csv
public void writeLine(FileWriter writer, String[] params, char separator) {
boolean firstParam = true;
StringBuilder stringBuilder = new StringBuilder();
String param = "";
for (int i = 0; i < params.length; i++) {
//get param
param = params[i];
log.info(param);
//if the first param in the line, separator is not needed
if (!firstParam) {
stringBuilder.append(separator);
}
//Add param to line
stringBuilder.append(param);
firstParam = false;
}
//prepare file to next line
stringBuilder.append("\n");
//add to file the line
log.info(stringBuilder.toString());
writer.append(stringBuilder.toString());
}
//get path of csv file (creates new one if its not exists)
String csvFile = "${projectHome}/tenant_details.csv";
String[] params = {"${Email}"};
FileWriter fileWriter = new FileWriter(csvFile, true);
writeLine(fileWriter, params, SEPARATOR);
//proper close to file
fileWriter.flush();
fileWriter.close();
当我在 Windows 计算机上运行脚本时,由于路径有反斜杠而失败。
如何在同一个 BeanShell Sampler 中将反斜杠转换为正斜杠,以便它可以在 Windows 和 MacOS 上运行?
最佳答案
您不需要将斜杠
/
替换为反斜杠\
,斜杠也适用于 Windows 平台的文件,您可以执行以下操作:new File("c:/Windows/system32/cmd.exe")
通常会解决。
不要在脚本中引用诸如
${projectHome}
和/或${Email}
之类的变量,请使用vars
简写反而。它代表JMeterVariables类实例并提供对范围内所有 JMeter 变量的读/写访问。所以你应该使用String csvFile = vars.get("projectHome") + "/tenant_details.csv";
和
String[] params = {vars.get("Email")};
自 JMeter 3.1 it is recommended to use JSR223 Test Elements and Groovy language for scripting因此,请考虑在下一个可用机会时迁移到 Groovy,因为 Beanshell(并且将会)在高负载时成为性能瓶颈。请参阅Apache Groovy - Why and How You Should Use It文章了解更多信息。
关于java - 如何使用 jmeter BeanShell 将反斜杠 (\) 替换为正斜杠 (/),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49699870/