代码之家  ›  专栏  ›  技术社区  ›  zjffdu

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

  •  7
  • zjffdu  · 技术社区  · 14 年前

    我在多线程环境中使用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();
        }
    }
    

    我在google上发现junit不能处理多线程单元测试,但是这两段代码有什么区别?谢谢

    5 回复  |  直到 6 年前
        1
  •  7
  •   Abhinav Sarkar    14 年前

    fail executor

    future.get ExecutionException

        2
  •  2
  •   Jonathan    14 年前

    ConcurrentUnit

    public class ExampleTest extends ConcurrentTestCase {
        private ExecutorService executor = Executors.newFixedThreadPool(10);
    
        public void test() throws Throwable {
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        threadFail("Failure message");
                    } finally {
                        resume();
                    }
                }
            });
    
            threadWait();
        }
    }
    

        3
  •  1
  •   Volker Stolz    14 年前

    fail get()

    newThreadId.join()

        4
  •  0
  •   user180100    14 年前
        5
  •  0
  •   Toby Daniel C. Sobral    14 年前