我有下面的界面
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();但是编译器告诉我有一个未处理的异常。Retrieve方法的定义如下:
public List<SomeClass> Retrieve() {
try {
interface1Object.Execute("");
}
catch (Exception exception) {
return new ArrayList<SomeClass>();
}
}mockito文档只展示了RuntimeException的用法,而我在StackOverflow上还没有看到类似的东西。我使用的是Java 1.7u25和mockito 1.9.5
发布于 2013-07-07 04:23:09
假设你的测试方法没有声明它抛出了Exception,那么编译器是绝对正确的。这一行:
when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());..。在Interface1的实例上调用Execute。这会抛出Exception,所以你需要捕捉它或者声明你的方法抛出了它。
我个人建议只声明测试方法抛出Exception。其他任何东西都不会关心这个声明,而且您也不会真的想要捕获它。
https://stackoverflow.com/questions/17506767
复制相似问题