尝试使用Mockito引发抛出检查异常的问题

Miy*_*ira 4 java mockito

我有下面的界面

public interface Interface1 {
    Object Execute(String commandToExecute) throws Exception;
}
Run Code Online (Sandbox Code Playgroud)

然后,我尝试进行模拟,以便可以测试将其调用的类的行为:

Interface1 interfaceMocked = mock(Interface1.class);
when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());
Interface2 objectToTest = new ClassOfInterface2(interfaceMocked);
retrievePrintersMetaData.Retrieve();
Run Code Online (Sandbox Code Playgroud)

但是编译器告诉我,有一个未处理的异常。Retrieve方法的定义是:

public List<SomeClass> Retrieve() {
    try {
        interface1Object.Execute("");
    }
    catch (Exception exception) {
        return new ArrayList<SomeClass>();
    }
}
Run Code Online (Sandbox Code Playgroud)

Mockito文档仅显示RuntimeException的使用,而我在StackOverflow上也没有看到类似的东西。我正在使用Java 1.7u25和Mockito 1.9.5

Jon*_*eet 5

假设您的测试方法未声明抛出异常Exception,那么编译器是绝对正确的。这行:

when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());
Run Code Online (Sandbox Code Playgroud)

...调用Execute的实例Interface1。那会抛出Exception,所以您要么需要捕获它,要么声明您的方法将其抛出。

我个人建议仅声明测试方法throws Exception。没有别的要关心那个声明了,您真的不想抓住它。