一、核心步骤 1.创建一个Java 工程;
2.将JMeter的lib目录下的jar文件添加进此工程的Build Path; ApacheJMeter_core.jar(必须)、ApacheJMeter_java.jar(必须)、avalon-framework-4.1.4.jar、jorphan.jar、logkit-2.0.jar 后台3个为本地调试需要用到的包文件
3.创建一个类并实现JavaSamplerClient接口或继承AbstractJavaSamplerClient,并重写;
构建待测试 类:
public class MathTest { public String sayHello() { return "Hello" ; } public String sayHelloToPerson(String s) { if (s == null || s.equals( "" )) s = "nobody" ; return ( new StringBuilder()).append( "Hello " ).append(s).toString(); } public int sum( int a, int b) { return a+b; } public static void main(String args[]){ MathTest math = new MathTest(); System.out.println(math.sum(1 , 2 )); } }
public Arguments getDefaultParameters();设置可用参数及的默认值; public void setupTest(JavaSamplerContext arg0):每个线程测试前执行一次,做一些初始化工作; public SampleResult runTest(JavaSamplerContext arg0):开始测试,从arg0参数可以获得参数值; public void teardownTest(JavaSamplerContext arg0):测试结束时调用;
import org.apache.jmeter.config.Arguments; import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient; import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext; import org.apache.jmeter.samplers.SampleResult; import com.huize.common.MathTest; public class JavaTest extends AbstractJavaSamplerClient { private MathTest test= null ; private String a; private String b; private String resultData; private static long start = 0 ; private static long end = 0 ; public Arguments getDefaultParameters() { Arguments params = new Arguments(); params.addArgument("num1" , "" ); params.addArgument("num2" , "" ); return params; } public void setupTest(JavaSamplerContext arg0) { test = new MathTest(); a = arg0.getParameter("num1" ); b = arg0.getParameter("num2" ); start = System.currentTimeMillis(); } public SampleResult runTest(JavaSamplerContext arg0) { SampleResult sr = new SampleResult(); sr.setSamplerData("请求参数num1:" +a+ "\n请求参数num2:" +b); try { sr.sampleStart(); resultData = String.valueOf(test.sum(Integer.parseInt(a), Integer.parseInt(b))); if (resultData != null && resultData.length() > 0 ) { sr.setResponseData("结果是:" +resultData, null ); sr.setDataType(SampleResult.TEXT); } Thread.sleep(10 ); sr.setSuccessful(true ); } catch (Throwable e) { sr.setSuccessful(false ); e.printStackTrace(); } finally { sr.sampleEnd(); } return sr; } public void teardownTest(JavaSamplerContext arg0) { end = System.currentTimeMillis(); System.err.println("cost time:" + (end - start) + "毫秒" ); } }
4.Export为Runnable Jar File (注意:
打包时,JavaTest.java中main需要注释掉,否则JMeter无法运行 ) ;
5.将此jar包放入JMETER_HOME\lib\ext目录;
6.以管理员身份打开JMeter;
7.创建线程组、Java Request、查看结果树,进行测试;
转载地址: http://blog.csdn.net/luozhuwang/article/details/51882063