关于JUnit4无法支持多线程测试的解决方法
阅读原文时间:2023年07月08日阅读:1

转自:https://segmentfault.com/a/1190000003762719

其实junit是将test作为参数传递给了TestRunner的main函数。并通过main函数进行执行。

test函数在main中执行。如果test执行结束,那么main将会调用System.exit(0);即使还有其他的线程在运行,main也会调用System.exit(0);

System.exit()是系统调用,通知系统立即结束jvm的运行,即使jvm中有线程在运行,jvm也会停止的。所以会出现之前的那种情况。其中System.exit(0);的参数如果是0,表示系统正常退出,如果是非0,表示系统异常退出。

junit.textui.TestRunner
public static void main (String[] args) {
TestRunner aTestRunner = new TestRunner();
try {
TestResult r = aTestRunner.start(args);
if (!(r.wasSuccessful()))
System.exit (1);
System.exit(0);
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit(2);
}
}

  我用GroboTestingJUnit-1.2.1-core导入工程就能用JUnit进行多线程测试了

下载地址:

https://download.csdn.net/download/wangqingqi20005/9636371

——————————————————2018-4-15日更新————————————————————————

最好还是用main进行多线程测试,就算导入了GroboTestingJUnit-1.2.1-core.jar包还是会有bug

首先是代码部分:

thread2

运行部分代码:

test10运行结果:

main运行结果:

结果一目了然,不相信的同学可以试一下,我是推荐用main进行测试