实际上junit是不支持多线程的,但是我们可以使用插件,groboutils 就解决了这个问题。
<!-- https://mvnrepository.com/artifact/net.sourceforge.groboutils/groboutils-core -->
<dependency>
<groupId>net.sourceforge.groboutils</groupId>
<artifactId>groboutils-core</artifactId>
<version>5</version>
<scope>test</scope>
</dependency>
然后发现 groboutils 包根本就下载不下来,这个可以直接将 jar 包下载下来,下载地址:
https://oss.sonatype.org/content/repositories/opensymphony-releases/net/sourceforge/groboutils/groboutils-core/5/
将下载的 jar 包放在maven的下载路径下:
repository\net\sourceforge\groboutils\groboutils-core\5
接下来就是代码了,示例代码是测试 redis 分布式锁时写的:
public class Test {
@org.junit.Test
public void test() {
TestRunnable runner = new TestRunnable() {
@Override
public void runTest() throws Throwable {
String url = "http://localhost:8080/hello";
HttpGet get = new HttpGet(url);
CloseableHttpClient client = HttpClientBuilder.create().build();
CloseableHttpResponse response = client.execute(get);
response.close();
}
};
int runnerCount = 10;
// 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();
}
}
}