13

为什么我的单元测试在调试模式下成功,但在正常运行时失败?

public class ExecutorServiceTest extends MockitoTestCase{   
  private int numThreads;
  private ExecutorService pool;
  private volatile boolean interruptedBitSet;

  @Override
  public void setUp() {
    numThreads = 5;
    pool = Executors.newFixedThreadPool(numThreads);
  }

class TaskChecksForInterruptedBit implements Callable<String> {
    @Override
    public String call() throws Exception {
      interruptedBitSet = false;
      while (!Thread.currentThread().isInterrupted()) {
      }
      interruptedBitSet = Thread.currentThread().isInterrupted();
      return "blah";
    }
  }

public void testCancelSetsInterruptedBitInCallable() throws Exception {
    interruptedBitSet = false;
    final Future<String> future = 
        pool.submit(new TaskChecksForInterruptedBit());
    final boolean wasJustCancelled = future.cancel(true);
    assertTrue(wasJustCancelled);

    // Give time for the thread to notice the interrupted bit and set the flag
    Thread.sleep(5000);

    // This succeeds when stepping through w/ a debugger, but fails when running
    // the test straight. WHY?
    assertTrue(interruptedBitSet);

    assertTrue(future.isDone());
    assertTrue(future.isCancelled());
  }
}
4

5 回答 5

3

原因几乎可以肯定是调试器中的断点正在暂停主线程,但没有暂停任何后台线程 - ExecutorService 中的那些。在 Eclipse 中调试时,您可以更改断点以停止所有线程,而不仅仅是主线程。

当不调试任务的提交和立即取消时,您会在任务运行一次之前取消任务。尝试在这些行之间添加睡眠延迟:

final Future<String> future =  pool.submit(new TaskChecksForInterruptedBit());
Thread.sleep(1000);
final boolean wasJustCancelled = future.cancel(true);
于 2013-03-02T00:33:44.613 回答
2

您必须确保您的任务真正开始运行。它甚至可能在它有机会之前被取消。

public class ExecutorServiceTest {
    private int numThreads;
    private ExecutorService pool;
    private volatile boolean interruptedBitSet;
    private static final CountDownLatch latch = new CountDownLatch(1);

    @Before
    public void setUp() {
        numThreads = 5;
        pool = Executors.newFixedThreadPool(numThreads);
    }

    class TaskChecksForInterruptedBit implements Callable<String> {
        @Override
        public String call() throws Exception {
            interruptedBitSet = false;
            latch.countDown();
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println(System.currentTimeMillis());
            }
            System.out.println("haha");
            interruptedBitSet = Thread.currentThread().isInterrupted();
            return "blah";
        }
    }

    @Test
    public void testCancelSetsInterruptedBitInCallable() throws Exception {
        final Future<String> future =
                pool.submit(new TaskChecksForInterruptedBit());
        interruptedBitSet = false;
        latch.await();
        final boolean wasJustCancelled = future.cancel(true);
        Assert.assertTrue(wasJustCancelled);

        // Give time for the thread to notice the interrupted bit and set the flag
        Thread.sleep(5000);

        // This succeeds when stepping through w/ a debugger, but fails when running
        // the test straight. WHY?
        Assert.assertTrue(interruptedBitSet);

        Assert.assertTrue(future.isDone());
        Assert.assertTrue(future.isCancelled());
    }
}
于 2013-03-02T00:46:13.243 回答
2

我知道这很旧,但我也遇到了同样的问题。我的问题是我有一个IEnumerable,我正在枚举和检查输出。

运行单元测试时,IEnumerable返回的顺序与调试时不同。这是IEnumerable的本质,只需添加一个OrderBy子句就可以解决我的问题。

我希望这可以帮助那里的人,因为找到它可能是一个令人沮丧的问题。

于 2014-07-16T08:08:47.917 回答
0

您应该在终止主线程之前检查所有线程是否都死了

private void shutdownExecutionService(ExecutorService executorService) {
    if (executorService != null) {
        try {
            executorService.shutdown();
            while (!executorService.awaitTermination(10, TimeUnit.HOURS)) {
                logger.info("Awaiting completion of threads.");
            }
        } catch (final InterruptedException e) {
            logger.error("Error while shutting down threadpool", e);
        }
    }
}
于 2017-01-04T14:14:38.477 回答
0

从在线课程中运行家庭作业时,我遇到了类似的问题。我添加到构建路径的课程中的分级程序使用了 JUnit4,我的 Eclipse 版本将 JUnit5 添加到任何新的测试用例中。我创建了一个新的 Java 项目,并将 JUnit5 添加到我的测试用例的构建浴中,没有评分器,它为我修复了它。希望这可以帮助。

于 2017-12-05T15:35:03.797 回答