1.背景
测试一个方法是否多线程并发安全,编写单元测试用例时发现Junit启动多线程会使用System.exit退出用例执行,无法进行多线程的测试,使用GroboUtils
2.配置
使用maven配置依赖
<dependency>
<groupId>net.sourceforge.groboutils</groupId>
<artifactId>groboutils-core</artifactId>
<version>5</version>
</dependency>
值得一提的是阿里云没有这个镜像,需要手动把云仓库指定为
https://oss.sonatype.org/content/repositories/opensymphony-releases
3.代码
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class RedPacketTest {
@Autowired
private RedpacketService redpacketService;
Logger log = LoggerFactory.getLogger(getClass());
@Test
public void redpacketTest() throws Throwable {
TestRunnable runner = new TestRunnable() {
@Override
public void runTest() throws Throwable {
// TODO 需要测试的业务方法
}
};
int runnerCount = 100;
// Rnner数组,相当于并发执行多少个线程
TestRunnable[] trs = new TestRunnable[runnerCount];
for (int i = 0; i < runnerCount; i++) {
trs[i] = runner;
}
// 用于执行多线程测试用例的Runner,将前面定义的单个Runner组成的数组传入
MultiThreadedTestRunner mttr = new MultiThreadedTestRunner(trs);
// 并发执行数组里定义的内容
mttr.runTestRunnables();
}
}