整理了一批jmeter常用的beanshell脚本供大家参考!
时间戳
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; try{ Date date =new Date(); //获取当前时间 SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String nowDate = sf.format(date); Calendar cal = Calendar.getInstance(); cal.setTime(sf.parse(nowDate)); cal.add(Calendar.DAY_OF_YEAR,+0); String orderDate = sf.format(cal.getTime()); cal.add(Calendar.DAY_OF_YEAR,+365); String senderDate = sf.format(cal.getTime()); vars.put("orderDate",orderDate); //参数可以调用 vars.put("senderDate",senderDate); //参数可以调用 } catch(Exception e){ }
下载文件
import java.io.*;
byte[] result = prev.getResponseData();
String file_name = "D:\\gongju\\apache-jmeter-3.2\\bin\\download\\sqlEnt_${id}.zip";
File file = new File(file_name);
FileOutputStream out = new FileOutputStream(file);
out.write(result);
out.close();
保存响应内容
FileWriter fstream = new FileWriter("XXX",true);
BufferedWriter out =new BufferedWriter(fstream);
out.write(vars.get("AAA")+","+ vars.get("BBB"));
out.write(System.getProperty("line.separator"));
out.close();
fstream.close();
断言
import java.io.UnsupportedEncodingException;
import org.apache.jmeter.assertions.AssertionResult;
import org.json.*;
String str = prev.getResponseDataAsString();
String result = "";
try {
result = java.net.URLDecoder.decode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
JSONObject data_obj=new JSONObject(str);
String result1 = data_obj.get("dockedContact").get("name").toString();
if(result1.contains("zhufc")) {
Failure = true;
FailureMessage = "断言成功";
log.info("断言成功");
}else{
Failure = false;
FailureMessage = "断言失败";
}
连接数据库
import java.sql.*;
import java.util.*;
import java.lang.*;
import org.apache.regexp.*;
import org.json.*;
//一:数据库取值
String drive = "org.gjt.mm.mysql.Driver";
String url = "jdbc:mysql://192.168.204.129:3306/";
String dbName = "aiopms";
String user = "root";
String pass = "000000";
String history = "";
String response = "";
String failuer = "";
String query ="SELECT projectid From pms_projects Where name ='测试项目' order by 'desc' limit 1";
Connection Mycon = null;
Statement Mystmt = null;
ResultSet Myrset = null;
try{Mycon = DriverManager.getConnection(url+dbName, user, pass);} catch(SQLException e){}
Mystmt = Mycon.createStatement();
Myrset = Mystmt.executeQuery(query);
while (Myrset.next()){history = Myrset.getString(1);}Myrset.close();Mystmt.close();if(history == "")
{Failure = true;FailureMessage = "连接数据库失败";
}
浮点时间戳转换为标准时间
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
//10位的秒级时间戳
long time1 = ${time};//获取时间戳变量
String result1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time1 * 1000));
log.info("10位时间戳(秒)--->Date:" +result1);//13位的毫秒级时间戳
//double time2 = 1515730332000d;
//String result2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time2);
//System.out.println("13位数的时间戳(毫秒)--->Date:" + result2);
解析jsonlist
利用beanshell获取到json响应,然后通过JSONObject 和JSONArray 将数组解析,遍历数组的length之后,提取参数值
我们需要解析如下的json响应,提取出中间的Name和population
//导入json包
import org.json.*;
//获取获取请求的返回值
String response_data = prev.getResponseDataAsString();
//日志打印获取请求的返回值
log.info(response_data);
//将String类型的返回值构造成JSONObject对象
JSONObject data_obj = new JSONObject(response_data);
//获取作为下一个请求post的参数值Province(两种方式)
//String Provincelist_str = data_obj.get("Province").toString();
JSONArray Provincelist_str = data_obj.getJSONArray("Province");
//log.info(Provincelist_str);
//获取Province数组的长度
int len = Provincelist_str.length(); String strlen = Integer.toString(len);vars.put("MessageNum",strlen);
log.info(strlen);
int i = 0;
for(;i < len;++i)
{
//获取 data[ i ] 数组对象
JSONObject jsonTemp = (JSONObject)Provincelist_str.getJSONObject(i);
switch(i)
{
case 0:
//两种提取参数的写法
String NameItems = jsonTemp.getString("Name");
// String NameItems = jsonTemp.get("Name").toString();
// 两种打印参数的方法
// vars.put("Name_1", jsonTemp.getString("Name"));
vars.put("Name_1", NameItems);
log.info(NameItems);
}
}
递归创建多级目录
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile; StringBuffer fileBuf=new StringBuffer(); String filePar = "D:\\\目录1\\目录2";File myPath = new File( filePar ); if ( !myPath.exists()){myPath.mkdirs(); System.out.println("创建文件夹路径为:"+ filePar); } String filename = "列表.csv";try { FileWriter fw = new FileWriter(filePar + "\\\" + filename,true);String originalLine = “”+"\n";System.out.println("*** "+ originalLine); fw.write(originalLine); fw.close(); } catch (IOException e) { e.printStackTrace(); }
常用内置变量
1.log 打印日志,写入信息到jmeber.log文件。2.SampleResult 获取SampleResult对象,能通过这个对象获取想要的信息。3.Response 获取Response对象,能通过这个对象获取响应信息。4.Failure 查看接口调使用能否成功,假如返回false是成功的,true是失败的。5.FailureMessage 失败信息,没有设置的时候失败信息是空的,能set这个信息。6.ResponseData 获取response body类型是byte[]。7.ResponseCode 返回接口code成功是200。8.ResponseMessage 获取msg成功是OK。9.ResponseHeaders 获取接口服务端返回的头部信息。10.RequestHeaders 获取用户端请求的头部信息。11.SampleLabel 获取接口请求的名称。12.SamplerData 获取请求的url和body。13.ctx 代表上下文信息,能直接用。14.vars即JMeterVariables,操作jmeter变量,这个变量实际引用了JMeter线程中的局部变量容器(本质上是Map),常用方法:a) vars.get(String key):从jmeter中获得变量值;b) vars.put(String key,String value):数据存到jmeter变量中;15.prev 获取前面的sample返回的信息,常用方法:a) prev.getResponseDataAsString():获取响应信息。b) prev.getResponseCode() :获取响应code。
调用cmd文件
String command = "cmd /c start D:\\apache-jmeter-3.2\\负载.bat";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
GUI小命令
button = new JButton( "登录" );
frame = new JFrame( "My Frame" );
frame.getContentPane().add( button, "Center" );
frame.pack();
frame.setVisible(true);