所以..。
我有这个实用工具类,它在初始调用在给定时间之后没有返回之后执行重试(理论上是对任何事情),并且一直这样做,直到任何源返回数据或所有调用都耗尽为止。这使用ExecutorCompletionService的.poll方法触发何时重试。
final RetrySources[] retrySources = getRetrySources(originalSource);
Future<T> resultFuture = null;
final List<Future<T>> futures = new ArrayList<>(retrySources.length);
for (int tryIndex = 0; tryIndex < retrySources.length && resultFuture == null; tryIndex++) {
final int tryIndexCopy = tryIndex;
futures.add(ecs.submit(() -> client.call(retrySources[tryIndexCopy], tryIndexCopy)));
resultFuture = ecs.poll(millisBeforeRetry, TimeUnit.MILLISECONDS);
}
if (resultFuture == null) {
resultFuture = ecs.take();
}
return resultFuture.get();...my的问题是,我正在重写测试,而不是使用睡眠,而是使用CountDownLatch。看看下面我的一个测试..。
@Test
public void call_firstRetryFinishesAfterLimitButBeforeSecondRetryDoes_triggersSecondRetryButUsesFirstResult() throws Exception {
final String readResult1 = "a";
final String readResult2 = "b";
final CountDownLatch signal1 = new CountDownLatch(1);
final CountDownLatch signal2 = new CountDownLatch(1);
expect(mockReadOperation.call(readOptions[0], 0)).andStubAnswer(() -> {
signal1.await(); // This causes the test to spin forever
// Thread.sleep(1000); // Swapping the line above for this, makes it work
return readResult1;
});
expect(mockReadOperation.call(readOptions[1], 1)).andStubAnswer(() -> {
signal1.countDown();
signal2.await(); // For this test case, make the second retry never return
return readResult2;
});
replay(mockReadOperation);
final ReadOption readOption = ReadOption.primary();
final String result = subject.call(readOption);
assertThat(result).isEqualTo("a");
}...and注意到我的ExecutorCompletionService是定义的..。
private final ExecutorCompletionService executorCompletionService = new ExecutorCompletionService(Executors.newFixedThreadPool(2));...since --我的测试在主线程中运行,每个调用都运行它自己的线程作为ExecutorCompletionService池的一部分,我不明白为什么让signal1.await();使测试永远旋转,并注意到注释,即切换单行以进行睡眠,会导致测试通过。
任何帮助都是非常感谢的。
发布于 2018-06-09 04:36:52
这可能是由于您正在激活(执行)模拟的replay(mockReadOperation);。??
注意:我从来没有使用过简单的模拟,但是一个快速的google显示,replay激活了模拟,这似乎符合答案,我可能错了。
如果我是对的,而且您总是必须使用replay模拟,那么也许解决方案是,切换到Mockito :p!
https://stackoverflow.com/questions/50769345
复制相似问题