* MTTR創(chuàng)建以后,調(diào)用runTestRunnables()方法來運行它
*/
public void testExampleThread()
throws Throwable {
//實例化 TestRunnable 類
TestRunnable tr1, tr2, tr3;
tr1 = new DelayedHello("1");
tr2 = new DelayedHello("2");
tr3 = new DelayedHello("3");
//把實例傳遞給 MTTR
TestRunnable[] trs = {tr1, tr2, tr3};
MultiThreadedTestRunner mttr =
new MultiThreadedTestRunner(trs);
//執(zhí)行MTTR和線程
mttr.runTestRunnables();
}
/**
* 標準的 main() 和 suite() 方法
*/
public static void main (String[] args) {
String[] name =
{ ExampleTest.class.getName() };
junit.textui.TestRunner.main(name);
}
public static Test suite() {
return new TestSuite(ExampleTest.class);
}
}
上面的例子中,每個線程將會在你發(fā)出測試指令后,在2到5秒之間向你返回它們的輸出,它們不僅按時間顯示,而且是以一個隨機的順序來顯示。這個單元測試只有所有的線程都執(zhí)行完成后才會結(jié)束。由于外加了MultiThreadedTestRunner,所以Junit繼續(xù)執(zhí)行測試用例之前,必須耐心的等待TestRunnables執(zhí)行完成它們的工作,做為可選項,你可以為MultiThreadedTestRunner的執(zhí)行分配大的執(zhí)行時間(這樣以便你脫離線程,而不掛起測試)。
要編譯運行ExampleTest,你必須在你的CLASSPATH環(huán)境變量中指定junit.jar和GroboUtils-2-core.jar兩個類庫的位置。這樣你會看到每人線程以隨機的順序來輸出 “Delayed Hedllo World”
結(jié)束語
寫一個多線程的單元測試不用感到苦腦,GroboUtils類庫為編寫多線程的單元測試提供了一個清晰簡單的API接口,通過把這個類庫添加到你的工具包中,你可以把單元測試擴展到模擬繁重的WEB網(wǎng)絡通訊和并發(fā)的數(shù)據(jù)庫處理,以及對你的同步方法進行壓力測試。