接口测试 jmeter BeanShell 参数化随机生成一列数组放入到接口请求参数中

萧帅 · 2021年08月24日 · 最后由 中通科技测试 回复于 2021年08月30日 · 3116 次阅读

接口参数:
{
"barcodeList": ["8038249", "8055636", "5006396"],

"orderSourId": "30",
"siteNo": "A260"
}

创建 csv 文件

业务场景是从一列数据随机取值生成一组数组,并放入到接口请求参数

添加 BeanShell PreProcessor

代码如下:

import org.apache.jmeter.services.FileServer;
String baseDir=FileServer.getFileServer().getBaseDir(); 

public static String lineContent(int lineNumber) throws IOException {
    File file = new File(baseDir+"/starsBarCode.csv"); \\文件路径
    FileReader fileReader = new FileReader(file);
    InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
    BufferedReader reader = new BufferedReader(isr);
    String csv = "";
    int lines = 0;
    String content = "";
    while (csv != null) {
        lines++;
        csv = reader.readLine();
        if (lines == lineNumber) {
            content = csv;
        }
    }
    reader.close();
    fileReader.close();
    log.info("content---------------"+content);
    return content;
}

// 获取随机数
public static int getRand(int max, int min) {
    Random random = new Random();
    return random.nextInt(max) % (max - min + 1) + min;
}

public static ArrayList getParameters() throws IOException{
    ArrayList list=new ArrayList();
    while (list.size() !=3) {
        int lineNumber = getRand(105, 2); //行总数,随机2个值
        String lineContent = lineContent(lineNumber);
        if (!list.contains(lineContent)) {
            list.add(lineContent);
        }
    }
   return list;
}

ArrayList list  = getParameters();
List barcodeList = new ArrayList();
for(int i=0;i<list.size();i++){
     String line = list.get(i);
     barcodeList.add(line);
}
 log.info(barcodeList.toString());
 vars.put("barcodeList",barcodeList.toString());

运行后的结果

共收到 2 条回复 时间 点赞

欢迎大佬指点,看看有没有最优方案参考,再次感谢!!

放到 beanshell 中看起来是一个不错的选择。要考虑如下几个点:
1、如果这列数据不多,可以直接放到 banshell 中,避免高并发时文件读取对性能产生消耗。
2、也可以交文件放到 Jmeter 的 setup 中只读一次,这样也可以避免性能损耗。

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册