今天测试SimpleDateFormat时用到多线程,但最初Junit并不理想,Mark一下。
Junit多线程测试如下,直接run会发现程序没有任何异常,但debug时SimpleDateFormatUtil却ParseException异常,说明Junit在多线程下Test是有bug的。【SimpleDateFormatUtil为Date解析工具类】
@Test
public void threadTest() {
for (int i = 0; i < 3; i++) {
new SimpleThread().start();
}
}
private static class SimpleThread extends Thread {
@Override
public void run() {
try {
System.out.println(this.getName() + ":" + SimpleDateFormatUtil.parse("2015-12-23 15:00:00"));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
public static transient void main(String args[]){
runMainAndExit(new RealSystem(), args);
}
private static transient void runMainAndExit(JUnitSystem system, String args[]){
Result result = (new JUnitCore()).runMain(system, args);
System.exit(result.wasSuccessful() ? 0 : 1);
}
很明显,其调用了System.exit函数,将导致线程结束,而多线程甚至都来不及运行。
那么,我们该如何在多线程先进行Junit测试呢?【用main函数测试也是OK的】
@Test public void threadTest() throws Throwable { TestRunnable[] testRunnables = new TestRunnable[NUM_THREAD]; for (int i = 0; i < testRunnables.length; i++) { testRunnables[i] = new SimpleThread(); } final MultiThreadedTestRunner multiThreadedTestRunner = new MultiThreadedTestRunner(testRunnables); multiThreadedTestRunner.runTestRunnables(); }
private static class SimpleThread extends TestRunnable { @Override public void runTest() { try { System.out.println(this.toString() + ":" + SimpleDateFormatUtil.parse("2015-12-23 15:00:00")); // System.out.println(this.toString()); // 正常输出所有线程名 } catch (ParseException e) { e.printStackTrace(); } } } |