在多线程环境中使用JUnit的奇怪问题 [英] Weird problem using JUnit in multi-thread environment

查看:144
本文介绍了在多线程环境中使用JUnit的奇怪问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在多线程环境中使用JUnit时遇到了问题。以下代码应该失败,但它实际上传递了eclipse。

I meet a weired problem when using JUnit in multi-thread environment. The following code should fail, but it actually pass in 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()来等待线程停止,在这种情况下它将失败。

And here'a another piece of code, here I use Future.get() to wait for thread stop, in this case it will fail.

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();
    }
}

我用google搜索它,发现JUnit无法处理多个 - 线程单元测试,但这两段代码之间的区别是什么?谢谢

I googled it and found that JUnit can not handle Multiple-thread unit testing,but what's the differences between these two pieces of code ? Thanks

推荐答案

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

JUnit cannot see the exceptions that occur in threads other than the thread in which the tests are running. In the first case, through an exception occurs by calling fail, it occurs in a separate thread run by the executor. Hence it is not visible to JUnit and the test passes.

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

In the second case, the same exception happens in the separate thread run by the executor but the exception is effectively "reported back" to the test thread when you call future.get. This is because future.get throws an ExecutionException if the computation of the future failed due to any exception. JUnit is able to see this exception and hence the test fails.

这篇关于在多线程环境中使用JUnit的奇怪问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆