使用JMeter测试JAVA接口,需要编写一个java类,继承AbstractJavaSampleClient,实现具体接口的调用,然后将此工程打包为一个jar包,放置在JMETER_HOME\lib\ext目录下,然后在JMeter里配置调用。
编写Java类,继承AbstractJavaSampleClient
打包 jar
将jar包放置至 JMETER_HOME\lib\ext 目录
JMeter里配置调用
1. 添加依赖
org.apache.jmeter
ApacheJMeter_java
2.7
2. 编写Java类
public class AdSearchServiceTest extendsAbstractJavaSamplerClient {private staticAdSearchService adSearchService;static{
ApplicationContext applicationContext= new ClassPathXmlApplicationContext("applicationContext.xml");
adSearchService= applicationContext.getBean("adSearchService", AdSearchService.class);
}//@OverridepublicSampleResult runTest(JavaSamplerContext javaSamplerContext) {
SampleResult sampleResult= newSampleResult();
String keyword= javaSamplerContext.getParameter("keyword");
AdSearchService.Param param= newAdSearchService.Param();
param.setKeyword(keyword);
param.setStart(1);
param.setLimit(10);long start =System.currentTimeMillis();
sampleResult.sampleStart();try{
SearchApiResult kievResult=adSearchService.search(param);
sampleResult.setResponseData(kievResult.getJson(),"utf-8");
sampleResult.setLatency(System.currentTimeMillis()-start);
sampleResult.setDataType(SampleResult.TEXT);
sampleResult.setSuccessful(true);
}catch(Exception e) {
sampleResult.setSuccessful(false);
}
sampleResult.sampleEnd();returnsampleResult;
}public static voidmain(String[] args) {
AdSearchServiceTest kiev= newAdSearchServiceTest();
Arguments arguments= newArguments();
arguments.addArgument("keyword", "微信");
JavaSamplerContext context= newJavaSamplerContext(arguments);
SampleResult result=kiev.runTest(context);
System.out.println(newString(result.getResponseData()));
}
}
注意以下参数:
sampleResult.sampleStart();
sampleResult.setSuccessful(true/false);
sampleResult.sampleEnd();
由于需要统计耗时以及请求成功与否的判断,需要设置以上参数,方便监听器统计测试信息
3. 打包
打包时需将相关依赖的包一同打包,否则会出现类找不到错误。(没试成功)
分开打包。打包时,将依赖 copy 至指定目录,然后将 jar 添加至 JMeter 的 ex t目录,最后在 JMeter 界面上指定依赖的 jar 包的目录。
maven 插件配置
org.apache.maven.plugins
maven-dependency-plugin
3.0.1
copy-dependencies
package
copy-dependencies
target/lib
junit
true
其中,target/lib 指明了依赖的 jar 输出的目录;
JMeter 配置依赖:
4. 将jar包放置在JMeter_home\lib\ext 目录下
5. 配置JMeter