gpt4 book ai didi

java - 单元测试在 Debug模式下成功,但在正常运行时失败

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:59:23 26 4
gpt4 key购买 nike

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

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

最佳答案

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

当不调试时,任务的提交和立即取消是如此之快,以至于您甚至在任务运行一次之前就取消了它。尝试在这些行之间添加 sleep 延迟:

final Future<String> future =  pool.submit(new TaskChecksForInterruptedBit());
Thread.sleep(1000);
final boolean wasJustCancelled = future.cancel(true);

关于java - 单元测试在 Debug模式下成功,但在正常运行时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15169104/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com