【jmeter系列】Jmeter將響應資料結果儲存到csv檔案的兩種方式(Bean Shell)
阿新 • • 發佈:2022-05-06
背景
日常介面測試,需要將介面返回值對應的欄位資料儲存下來
示例介面:
post請求:
https://dev-xxx-bot.igovee.com/text
{
"text":"I really need some meditative effects."
}
實現方法
方式一(Jmeter BeanShell取樣器提取介面)
介面獲取response資料:
{"cost_time":0.15606689453125,"emotion_class":{"label":"hope","score":0.2862275540828705},"entity":null,"entity_class":{"label":"plants","score":0.2635917663574219},"keywords":"fruit"}
jmeter執行緒組-JSR223 Sampler
程式碼例項:
//匯入json包 import org.json.JSONObject; import org.json.JSONArray; import org.apache.jmeter.samplers.SampleResult SampleResult rsp =ctx.getPreviousResult() String response_data = rsp.getResponseDataAsString() //獲取上一個介面返回資料,此處是String型別 log.info("\n" + response_data) //將String型別的返回值構造成JSONObject物件 JSONObject jsonstring=new JSONObject(response_data); //放進json物件裡 String cost_time=jsonstring.get("cost_time").toString(); //取出cost_time對應的value值 String score=jsonstring.get("emotion_class").get("score").toString(); //取出score對應的value值 vars.put("cost_time",cost_time); vars.put("score",score); log.info(cost_time); log.info(score); //寫入檔案 FileWriter fstream=new FileWriter("E:/gongju/jmeter/pc.csv",true);//本地儲存檔案路徑 BufferedWriter out = new BufferedWriter(fstream); out.write(cost_time);//提取出來的cost_time out.write(",");//換列 out.write(score);//提取出來的score out.write(System.getProperty("line.separator"));//換行 out.close(); fstream.close();
寫入CSV效果如下:
方式二(json提取器+BeanShell 取樣器)
1、json提取器提取出變數對應的value值
2、beanshell取樣器
示例程式碼:
File file=new File("E:\\gongju\\jmeter\\pc1.csv"); FileWriter fw=new FileWriter(file,true); BufferedWriter out=new BufferedWriter(fw); out.write(vars.get("cost_time")); out.write(",");//換列 out.write(vars.get("score"));//提取出來的score out.write(System.getProperty("line.separator"));//換行 out.close(); fw.close();
結果檔案:
備註:
JMeter執行時報Typed variable declaration : Class: JSONObject not found in namespace解決方案
因為${JMETER}\lib\下缺少json.jar包,下載連結如:
https://pan.baidu.com/s/1KFDUIq40BhUXcy2NYo7YkA 密碼: c91m
參考文件;https://blog.csdn.net/Python_BT/article/details/124191318