在多线程环境中使用JUnit的奇怪问题

zjf*_*fdu 7 java junit multithreading

在多线程环境中使用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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

而这里是另一段代码,在这里我使用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我用Google搜索并发现JUnit无法处理多线程单元测试,但这两段代码之间有什么区别?谢谢

Abh*_*kar 7

JUnit无法查看除运行测试的线程之外的线程中发生的异常.在第一种情况下,通过调用fail发生异常,它发生在由单独运行的线程中executor.因此,JUnit不可见,测试通过.

在第二种情况下,相同的异常发生在由运行的单独线程中,executor但异常在您调用时有效地"报告回"测试线程future.get.这是因为如果由于任何异常导致未来的计算失败,则future.get抛出一个ExecutionException.JUnit能够看到此异常,因此测试失败.