如何避免根据接口抛出异常的模拟方法的冗余捕获异常

How to avoid redundant catching exceptions of mocked methods which can throws exceptions according interface

我的单元测试中有以下代码:

 when(workspaceMock.getNamespaceRegistry()).thenReturn(namespaceRegistryMock);

方法getNamespaceRegistry可以抛出IOException

就java而言,提到的行是方法调用,我应该抓住它。

但另一方面我知道这个方法不能抛出异常,因为我在那里设置了这个方法的行为。在这里捕获异常看起来是多余的。

你能澄清一下这种情况并提出最佳做法吗?

您只需声明您的测试方法 throws Exception。通常,您当然不想在 production 代码上执行此操作,但这是 test 代码中的标准做法。