Java 尝试使用mockito抛出已检查异常时出现问题

Java 尝试使用mockito抛出已检查异常时出现问题,java,mockito,Java,Mockito,我有下面的界面 public interface Interface1 { Object Execute(String commandToExecute) throws Exception; } 然后我试图模拟它,以便测试将调用它的类的行为: Interface1 interfaceMocked = mock(Interface1.class); when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());

我有下面的界面

public interface Interface1 {
    Object Execute(String commandToExecute) throws Exception;
}
然后我试图模拟它,以便测试将调用它的类的行为:

Interface1 interfaceMocked = mock(Interface1.class);
when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());
Interface2 objectToTest = new ClassOfInterface2(interfaceMocked);
retrievePrintersMetaData.Retrieve();
但是编译器告诉我有一个未处理的异常。 检索方法的定义为:

public List<SomeClass> Retrieve() {
    try {
        interface1Object.Execute("");
    }
    catch (Exception exception) {
        return new ArrayList<SomeClass>();
    }
}
公共列表检索(){
试一试{
interface1Object.Execute(“”);
}
捕获(异常){
返回新的ArrayList();
}
}
mockito文档只显示RuntimeException的用法,我还没有在StackOverflow上看到类似的用法。
我使用的是Java 1.7u25和mockito 1.9.5,假设您的测试方法没有声明抛出异常,那么编译器是绝对正确的。这一行:

when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());
。。。调用
Interface1
实例上的
Execute
。它可以抛出异常,因此您需要捕获它或声明您的方法抛出它


我个人建议只声明测试方法抛出
异常
。其他任何东西都不会关心该声明,您真的不想捕获它。

如果您的方法返回某些内容并抛出错误,您不应该遇到问题。现在,如果您的方法返回void,您将无法抛出错误

现在真正的问题是,您没有测试接口是否抛出异常,而是测试在该方法中抛出异常时会发生什么

public List<SomeClass> Retrieve() {
    try {
        interface1Object.Execute("");
    }
    catch (Exception exception) {
        return handleException(exception);
    }
}

protected List<SomeClass> handleException(Exception exception) {
     return new ArrayList<SomeClass>();
}
公共列表检索(){
试一试{
interface1Object.Execute(“”);
}
捕获(异常){
返回句柄异常(异常);
}
}
受保护列表句柄异常(异常){
返回新的ArrayList();
}
然后调用handleException方法并确保它返回正确的内容。如果您需要确保您的接口正在抛出异常,那么对于您的接口类来说,这是一个不同的测试


您必须为一行代码创建一个方法,这可能看起来很糟糕,但如果您想要可测试的代码,有时会发生这种情况。

您可以使用Mockito的doAnswer方法来抛出检查过的异常,如下所示

Mockito.doAnswer(
          invocation -> {
            throw new Exception("It's not bad, it's good");
          })
      .when(interfaceMocked)
      .Execute(org.mockito.ArgumentMatchers.anyString());

解决了这个问题。我原以为莫基托会处理的。尚未习惯于检查异常的细节。