- /**
- * 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);
- }
- public void exit(int code) {
- System.exit(code);
- }
所以要想編寫多線程Junit測試用例,就必須讓主線程等待所有子線程執行完成後再退出。想到的辦法自然是Thread中的join方法。話又說回來,這樣一個簡單而又典型的需求,難道會沒有第三方的包支持麼?通過google,筆者很快就找到了GroboUtils這個Junit多線程測試的開源的第三方的工具包。
GroboUtils官網如下:
下載頁面:
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
- public void runTest() throws Throwable {
- // 測試內容
- }
- };
- 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);
- try {
- // 開發併發執行數組裏定義的內容
- mttr.runTestRunnables();
- } catch (Throwable e) {
- e.printStackTrace();
- }
- }