/** * 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測(cè)試用例,就必須讓主線程等待所有子線程執(zhí)行完成后再退出。想到的辦法自然是Thread中的join方法。話又說(shuō)回來(lái),這樣一個(gè)簡(jiǎn)單而又典型的需求,難道會(huì)沒(méi)有第三方的包支持么?通過(guò)google,很快就找到了GroboUtils這個(gè)Junit多線程測(cè)試的開(kāi)源的第三方的工具包。 GroboUtils官網(wǎng)下載解壓后 使用 GroboUtils-5\lib\core\GroboTestingJUnit-1.2.1-core.jar 這個(gè)即可 GroboUtils是一個(gè)工具集合,里面包含各種測(cè)試工具,這里使用的是該工具集中的jUnit擴(kuò)展. package com.junittest.threadtest; import java.util.ArrayList; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Set; import net.sourceforge.groboutils.junit.v1.MultiThreadedTestRunner; import net.sourceforge.groboutils.junit.v1.TestRunnable; import org.junit.Test; public class MutiThreadTest { static String[] path = new String[] { "" }; static Map<String, String> countMap = new Hashtable<String, String>(); static Map<String, String> countMap2 = new Hashtable<String, String>(); static Set<String> countSet = new HashSet<String>(); static List<String> list = new ArrayList<String>(); @Test public void testThreadJunit() throws Throwable { //Runner數(shù)組,想當(dāng)于并發(fā)多少個(gè)。 TestRunnable[] trs = new TestRunnable [10]; for(int i=0;i<10;i++){ trs[i]=new ThreadA(); } // 用于執(zhí)行多線程測(cè)試用例的Runner,將前面定義的單個(gè)Runner組成的數(shù)組傳入 MultiThreadedTestRunner mttr = new MultiThreadedTestRunner(trs); // 開(kāi)發(fā)并發(fā)執(zhí)行數(shù)組里定義的內(nèi)容 mttr.runTestRunnables(); } private class ThreadA extends TestRunnable { @Override public void runTest() throws Throwable { // 測(cè)試內(nèi)容 myCommMethod2(); } } public void myCommMethod2() throws Exception { System.out.println("===" + Thread.currentThread().getId() + "begin to execute myCommMethod2"); for (int i = 0; i <10; i++) { int a = i*5; System.out.println(a); } System.out.println("===" + Thread.currentThread().getId() + "end to execute myCommMethod2"); } } |