jmeter下实现Java请求
- 建立Java或maven工程并添加jmeter需要依赖的jar包,主要引入Jmeter的lib/ext下的jar包
- 自定义类extends AbstractJavaSampleClient implements Serializable
- 定义需要的默认参数key以及默认参数value
例如:
private String vin_Name = "vinStr";
private String default_vin = "LSFGM21H1KD500531";
private String loginNum_Name = "loginNum";
private String default_loginNum = "1";
private String host_Name = "host";
private String default_host = "10.130.210.87";
private String port_Name = "port";
private String default_port = "8010";
private String userName_Name = "userName";
private String default_userName = "zzzzzzzzzzzz";
private String password_Name = "password";
private String default_password = "zzzzzzzzzzzzzzzzzzzz";
private String timeOut_name = "timeout";
private String default_timeOut = "3000";
private String countNum_name = "countNum";
private String default_countNum = "1";
以下定义的是非界面展示变量,仅用于脚本使用
private Boolean assertion = false;
private Socket socket = null;
private OutputStream out = null;
private InputStream in = null;
private Vehicle vehicle = null;
- 重写getDefaultParameters方法,用于在jmeter页面展示定义的默认值. List item
@Override
public Arguments getDefaultParameters() {
Arguments params = new Arguments();
params.addArgument(vin_Name, default_vin);
params.addArgument(loginNum_Name, default_loginNum);
params.addArgument(host_Name, default_host);
params.addArgument(port_Name, default_port);
params.addArgument(userName_Name, default_userName);
params.addArgument(password_Name, default_password);
params.addArgument(timeOut_name, default_timeOut);
params.addArgument(countNum_name, default_countNum);
return params;
}
- 编写测试代码,sampleStart与samplerEnd之间的代码为实际运行的代码,sampleStart-sampleEnd之前运行的代码就是sampler的运行时间
SampleResult result = new SampleResult();
result.sampleStart();
try {
socket.setSoTimeout(Integer.valueOf(default_timeOut));
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 如果是第一次运行时,运行登录
if (1!= Long.valueOf(default_countNum)) {
try {
System.out.println("上报数据是:" + ArrayUtils.toString(reportData));
out.write(reportData);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
System.out.println("平台登录数据是:" + ArrayUtils.toString(platformLogin));
out.write(platformLogin);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
while (true) {
try {
if ((in.read(buf)) != -1) {
if (buf[3] == (byte) 1) {
System.out.println("响应数据是:" + ArrayUtils.toString(buf));
assertion = true;
}
break;
}
} catch (IOException e) {
// TODO Auto-generated catch block
result.setResponseCode("500");
result.setResponseData("响应超时");
e.printStackTrace();
break;
}
}
// sampler结束
result.sampleEnd();
- 将工程打成jar包,并放入apache-jmeter-5.2.1\lib\ext目录下,注意在编写脚本过程中使用到的第三方的jar包也必须一并放入到该目录下
7.打开jmeter建立Java请求即可