public Arguments getDefaultParameters():設(shè)置可用參數(shù)及的默認值;
public void setupTest(JavaSamplerContext arg0):每個線程測試前執(zhí)行一次,做一些初始化工作;
public SampleResult runTest(JavaSamplerContext arg0):開始測試,從arg0參數(shù)可以獲得參數(shù)值;
public void teardownTest(JavaSamplerContext arg0):測試結(jié)束時調(diào)用;
4.Export為Runnable Jar File;
|
package test;
import java.io.File;
import java.io.PrintWriter;
public class OutputService {
public static void output(String filename,int a, int b) throws Exception {
PrintWriter out = new PrintWriter(new File(filename));
out.write(a+":"+b);
out.close();
}
}
|
package test;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
public class PerformenceTest implements JavaSamplerClient {
private SampleResult results;
private String a;
private String b;
private String filename;
// 設(shè)置傳入的參數(shù),可以設(shè)置多個,已設(shè)置的參數(shù)會顯示到Jmeter的參數(shù)列表中
public Arguments getDefaultParameters() {
Arguments params = new Arguments();
params.addArgument("filename", "0");//設(shè)置參數(shù),并賦予默認值0
params.addArgument("a", "0");//設(shè)置參數(shù),并賦予默認值0
params.addArgument("b", "0");//設(shè)置參數(shù),并賦予默認值0
return params;
}
// 初始化方法,實際運行時每個線程僅執(zhí)行一次,在測試方法運行前執(zhí)行
public void setupTest(JavaSamplerContext arg0) {
results = new SampleResult();
}
// 測試執(zhí)行的循環(huán)體,根據(jù)線程數(shù)和循環(huán)次數(shù)的不同可執(zhí)行多次
@Override
public SampleResult runTest(JavaSamplerContext arg0) {
b = arg0.getParameter("b"); // 獲取在Jmeter中設(shè)置的參數(shù)值
a = arg0.getParameter("a"); // 獲取在Jmeter中設(shè)置的參數(shù)值
filename = arg0.getParameter("filename"); // 獲取在Jmeter中設(shè)置的參數(shù)值
results.sampleStart();// jmeter 開始統(tǒng)計響應時間標記
try {
OutputService test = new OutputService();
test.output(filename,Integer.parseInt(a), Integer.parseInt(b));
results.setSuccessful(true);
// 被測對象調(diào)用
} catch (Throwable e) {
results.setSuccessful(false);
e.printStackTrace();
} finally {
results.sampleEnd();// jmeter 結(jié)束統(tǒng)計響應時間標記
}
return results;
}
// 結(jié)束方法,實際運行時每個線程僅執(zhí)行一次,在測試方法運行結(jié)束后執(zhí)行
public void teardownTest(JavaSamplerContext arg0) {
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Arguments params = new Arguments();
params.addArgument("a", "0");//設(shè)置參數(shù),并賦予默認值0
params.addArgument("b", "0");//設(shè)置參數(shù),并賦予默認值0
JavaSamplerContext arg0 = new JavaSamplerContext(params);
PerformenceTest test = new PerformenceTest();
test.setupTest(arg0);
test.runTest(arg0);
test.teardownTest(arg0);
}
}
Export 為 Runnable Jar File;
|