【jmeter系列】Jmeter将响应数据结果保存到csv文件的两种方式(Bean Shell)
背景
日常接口测试,需要将接口返回值对应的字段数据保存下来
示例接口:
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
本文来自博客园,作者:橘子偏爱橙子,转载请注明原文链接:https://www.cnblogs.com/xfbk/p/16225484.html