【发布时间】:2022-11-03 16:46:18
【问题描述】:
我正在尝试编写一个需要覆盖 catch 块的测试用例。 catch 块捕获InterruptedException 或ExecutionException,两者都在Future 对象的.get() 方法的方法签名中。我正在尝试使用来自 Mockito 的 thenThrow 模拟 InterruptedException,当调用 Future 对象的 .get() 方法时,控件进入未覆盖的 catch 块。
futureData 是 List<Future<Class>> 类型,结果是 Future<Class> 对象。
futureData.forEach(result -> {
try {
enginesData.add(result.get()); // the method I am using to force an exception using Mockito
} catch (InterruptedException | ExecutionException e) {
// the catch block I am trying to cover
}
});
下面是我的测试用例:
@Test
public void testInterruptedException () throws ExecutionException, InterruptedException {
...
InterruptedException interruptedException = new InterruptedException("Interrupted Exception");
when(oneFutureData.get()).thenThrow(CompletableFuture.completedFuture(interruptedException));
...
}
我尝试连续编写thenThrow 和doThrow,但它仍然没有覆盖catch 块。可能是因为我试图模拟 Future 对象并模拟 Future 类中的方法吗?
【问题讨论】:
-
futureData是空的吗? -
如果您想从
get电话中接听InterruptedException,那么为什么不在那个电话上简单地thenThrow(interruptedException)呢?毕竟,catch (InterruptedException不会赶上CompletableFuture -
@dan1st 不,它包含一个
List<Future<Class>>包含两个Future<Class>元素。这可能与未来 Mockito 没有检测到被调用的方法有关,因此它没有抛出异常? -
@racraman 是的,我做到了。我的测试用例上有一个
when(futureData.get()).thenThrow(interruptedException)。