本文出自One Coder部落格,轉載請務必註明出處: http://www.coderli.com/archives/multi-thread-junit-grobountils/
寫過Junit單元測試的同學應該會有感覺,Junit本身是不支援普通的多線程測試的,這是因為Junit的底層實現上,是用System.exit退出用例執行的。JVM都終止了,在測試線程啟動的其他線程自然也無法執行。JunitCore代碼如下:
/** * Run the tests contained in the classes named in the <code>args</code>. * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1. * Write feedback while tests are running and write * stack traces for all failed tests after the tests all complete. * @param args names of classes in which to find tests to run */ public static void main(String... args) { runMainAndExit(new RealSystem(), args); } /** * Do not use. Testing purposes only. * @param system */ public static void runMainAndExit(JUnitSystem system, String... args) { Result result= new JUnitCore().runMain(system, args); system.exit(result.wasSuccessful() ? 0 : 1); }
RealSystem.java:
public void exit(int code) { System.exit(code); }
所以要想編寫多線程Junit測試案例,就必須讓主線程等待所有子線程執行完成後再退出。想到的辦法自然是Thread中的join方法。話又說回來,這樣一個簡單而又典型的需求,難道會沒有第三方的包支援麼。通過google,筆者很快就找到了GroboUtils這個Junit多線程測試的開源的第三方的工具包。 GroboUtils官網如下: http://groboutils.sourceforge.net/ 下載頁面: http://groboutils.sourceforge.net/downloads.html Maven依賴方式:
<dependency> <groupId>net.sourceforge.groboutils</groupId> <artifactId>groboutils-core</artifactId> <version>5</version> </dependency>
註:需要第三方庫支援:
| Repository |
Opensymphony Releases |
| Repository url |
https://oss.sonatype.org/content/repositories/opensymphony-releases |
依賴好Jar包後就可以編寫多線程測試案例了。上手很簡單:
/** * 多線程測試案例 * * @author lihzh(One Coder) * @date 2012-6-12 下午9:18:11 * @blog http://www.coderli.com */ @Test public void MultiRequestsTest() { // 構造一個Runner TestRunnable runner = new TestRunnable() { @Override