junit 模拟压力测试
junit 模拟多线程压力测试
在生产中经常会遇到关于压力测试的问题,如何在实际生产中测试程序所承受的压力,对于开发来说并不是一件容易的事,下面介绍junit 多线程测试。
直接上代码
package com.bypay.bingfa;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.junit.Test;
import net.sourceforge.groboutils.junit.v1.MultiThreadedTestRunner;
import net.sourceforge.groboutils.junit.v1.TestRunnable;
public class BFRequestsTest {
@Test
public void BFRequestsTest() {
// 构造一个Runner
TestRunnable runner = new TestRunnable() {
@Override
public void runTest() throws Throwable {
// 测试内容
testRun();
}
};
int runnerCount = 1000; // Rnner数组,想当于并发多少个。
TestRunnable[] trs = new TestRunnable[runnerCount];
for (int i = 0; i < runnerCount; i++) {
trs[i] = runner;
}
// 用于执行多线程测试用例的Runner,将前面定义的单个Runner组成的数组传入
MultiThreadedTestRunner mttr = new MultiThreadedTestRunner(trs);
try {
// 开发并发执行数组里定义的内容
mttr.runTestRunnables();
} catch (Throwable e) {
e.printStackTrace();
}
}
public void testRun() {
try {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("http://58.246.136.11:8029/front/inlet!deal.ac");
String date = "{\"name\": \"wangjx\"}";
((PostMethod) method).addParameter("data", date);
HttpMethodParams param = method.getParams();
param.setContentCharset("UTF-8");
client.executeMethod(method);
// 打印服务器返回的状态
System.out.println("http 返回状态\n" + method.getStatusLine());
// 打印返回的信息
InputStream stream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
StringBuffer buf = new StringBuffer();
String line;
while (null != (line = br.readLine())) {
buf.append(line).append("\n");
}
System.out.println("调用接口返回数据\n" + buf.toString());
// 释放连接
method.releaseConnection();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}