在多线程环境中使用JUnit时遇到一个奇怪的问题。以下代码应该失败,但实际上会通过eclipse。
public class ExampleTest extends TestCase {
private ExecutorService executor = Executors.newFixedThreadPool(10);
private volatile boolean isDone = false;
public void test() throws InterruptedException, ExecutionException {
executor.submit(new Runnable() {
@Override
public void run() {
try {
fail();
} finally {
isDone = true;
}
}
});
while (!isDone) {
Thread.sleep(1000);
}
}
}
这是另一段代码,这里我使用Future.get()等待线程停止,在这种情况下它将失败。
public class ExampleTest extends TestCase {
private ExecutorService executor = Executors.newFixedThreadPool(10);
private volatile boolean isDone = false;
public void test() throws InterruptedException, ExecutionException {
Future future=executor.submit(new Runnable() {
@Override
public void run() {
try {
fail();
} finally {
isDone = true;
}
}
});
future.get();
}
}
我搜索了一下,发现JUnit无法处理多线程单元测试,但是这两段代码有什么区别?谢谢
JUnit无法查看在运行测试的线程以外的线程中发生的异常。在第一种情况下,通过调用fail
发生异常,它发生在由运行的单独线程中executor
。因此,它对于JUnit不可见,并且测试通过。
在第二种情况下,相同的异常发生在由所运行的单独线程中,executor
但是当您调用时,该异常实际上被“报告”回测试线程future.get
。这是因为future.get
抛出ExecutionException
,如果未来的计算有任何例外失败所致。JUnit能够看到此异常,因此测试失败。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句