1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 多线程的单元测试工具 - GroboUtils

多线程的单元测试工具 - GroboUtils

时间:2021-03-14 14:33:55

相关推荐

多线程的单元测试工具 - GroboUtils

写过Junit单元测试的同学应该会有感觉,Junit本身是不支持普通的多线程测试的,这是因为Junit的底层实现上,是用System.exit退出用例执行的。JVM都终止了,在测试线程启动的其他线程自然也无法执行。JunitCore代码如下:

/***Runthetestscontainedintheclassesnamedinthe<code>args</code>.*Ifalltestsrunsuccessfully,exitwithastatusof0.Otherwiseexitwithastatusof1.*Writefeedbackwhiletestsarerunningandwrite*stacktracesforallfailedtestsafterthetestsallcomplete.*@paramargsnamesofclassesinwhichtofindteststorun*/publicstaticvoidmain(String...args){runMainAndExit(newRealSystem(),args);}/***Donotuse.Testingpurposesonly.*@paramsystem*/publicstaticvoidrunMainAndExit(JUnitSystemsystem,String...args){Resultresult=newJUnitCore().runMain(system,args);system.exit(result.wasSuccessful()?0:1);}

RealSystem.java:

publicvoidexit(intcode){System.exit(code);}所以要想编写多线程Junit测试用例,就必须让主线程等待所有子线程执行完成后再退出。想到的办法自然是Thread中的join方法。话又说回来,这样一个简单而又典型的需求,难道会没有第三方的包支持么?通过google,笔者很快就找到了GroboUtils这个Junit多线程测试的开源的第三方的工具包。 GroboUtils官网如下: / 下载页面: /downloads.html Maven依赖方式: <dependency><groupId>net.sourceforge.groboutils</groupId><artifactId>groboutils-core</artifactId><version>5</version></dependency> 注:需要第三方库支持:依赖好Jar包后就可以编写多线程测试用例了。上手很简单: /***多线程测试用例**@authorlihzh(OneCoder)*@date-6-12下午9:18:11*@blog*/@TestpublicvoidMultiRequestsTest(){//构造一个RunnerTestRunnablerunner=newTestRunnable(){@OverridepublicvoidrunTest()throwsThrowable{//测试内容}};intrunnerCount=100;//Rnner数组,想当于并发多少个。TestRunnable[]trs=newTestRunnable[runnerCount];for(inti=0;i<runnerCount;i++){trs[i]=runner;}//用于执行多线程测试用例的Runner,将前面定义的单个Runner组成的数组传入MultiThreadedTestRunnermttr=newMultiThreadedTestRunner(trs);try{//开发并发执行数组里定义的内容mttr.runTestRunnables();}catch(Throwablee){e.printStackTrace();}}

执行一下,看看效果。怎么样,你的Junit也可以执行多线程测试用例了吧:)。

本文出自One Coder博客,出处:/archives/multi-thread-junit-grobountils/

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。