Jmeter中隨機讀取測試文件的內容
性能測試中需要測試這麽一個場景:測試數據是一堆的地址,存儲在一個文件中。為了模仿真實的用戶訪問場景,需要從這個文件中每次隨機選取地址,拼接在一個固定的域名後發送出去。看了半天jmeter的幫助文檔,也在網上搜了半天,用jmeter的Groovy腳本解決:
import java.text.*;
import java.io.*;
import java.util.*;
String csvTest = "test_data.csv";
//csvDir = vars.get("fileLocation");
String csvDir = "./";
ArrayList strList = new ArrayList();
try {
File file = new File(csvDir + csvTest);
if (!file.exists()) {
throw new Exception ("ERROR: file " + csvTest + " not found in " + csvDir + " directory.");
}
BufferedReader bufRdr = new BufferedReader(new FileReader(file));
String line = null;
while((line = bufRdr.readLine()) != null) {
strList.add(line);
}
bufRdr.close();
Random rnd = new java.util.Random();
log.info(strList.get(rnd.nextInt(strList.size())));
vars.put("data",strList.get(rnd.nextInt(strList.size())));
}
catch (Exception ex) {
IsSuccess = false;
log.error(ex.getMessage());
System.err.println(ex.getMessage());
}
這樣每次發請求時jmeter會隨機讀取“test_data.csv”這個文件中的內容,並存為data變量,在http request中設置Send Parameter With the Request,用${data}的方式把這個變量取出來就好了。
Jmeter中隨機讀取測試文件的內容