JUnit4 實際上不支持測試多線程程序精堕。
The article at http://www.planetgeek.ch/2009/08/25/how-to-find-a-concurrency-bug-with-java/describes a method of exposing concurrency bugs that adds a new assertion method assertConcurrent
.
該文章中提供了一個新的斷言方法來測試多線程程序:
assertConcurrent(final String message, final List<? extends Runnable> runnables, final int maxTimeoutSeconds)
-
final String message
:如果測試不通過,打印出的消息 -
final List<? extends Runnable> runnables
:需要測試的線程 -
final int maxTimeoutSeconds
:最長運行時間蒲障,單位 秒歹篓,如果超時,則測試不通過
該方法將需要測試的線程放入一個線程池中揉阎,并發(fā)執(zhí)行庄撮,最后判斷是否有異常發(fā)生,是否有超時發(fā)生毙籽。
示例如下:
如下的代碼會產(chǎn)生超時洞斯,測試不通過。
java.lang.AssertionError: Test Failed timeout! More than1seconds
public class JUnit4_Test {
@Test
public void test1() throws Exception {
List<Runnable> runnables = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
runnables.add(new MyRunnable());
}
assertConcurrent("Test Failed", runnables, 1);
}
public static void assertConcurrent(final String message, final List<? extends Runnable> runnables, final int maxTimeoutSeconds) throws InterruptedException {
final int numThreads = runnables.size();
final List<Throwable> exceptions = Collections.synchronizedList(new ArrayList<Throwable>());
final ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
try {
final CountDownLatch allExecutorThreadsReady = new CountDownLatch(numThreads);
final CountDownLatch afterInitBlocker = new CountDownLatch(1);
final CountDownLatch allDone = new CountDownLatch(numThreads);
for (final Runnable submittedTestRunnable : runnables) {
threadPool.submit(new Runnable() {
public void run() {
allExecutorThreadsReady.countDown();
try {
afterInitBlocker.await();
submittedTestRunnable.run();
} catch (final Throwable e) {
exceptions.add(e);
} finally {
allDone.countDown();
}
}
});
}
// wait until all threads are ready
assertTrue("Timeout initializing threads! Perform long lasting initializations before passing runnables to assertConcurrent", allExecutorThreadsReady.await(runnables.size() * 10, TimeUnit.MILLISECONDS));
// start all test runners
afterInitBlocker.countDown();
assertTrue(message + " timeout! More than" + maxTimeoutSeconds + "seconds", allDone.await(maxTimeoutSeconds, TimeUnit.SECONDS));
} finally {
threadPool.shutdownNow();
}
assertTrue(message + "failed with exception(s)" + exceptions, exceptions.isEmpty());
}
}
class MyRunnable implements Runnable {
public void run() {
try {
Thread.sleep(10000);
} catch (Exception e) {
} finally {
}
}
}