尝试使用 mockito 抛出检查异常的问题 [英] Issues trying throw checked exception with mockito

查看:209
本文介绍了尝试使用 mockito 抛出检查异常的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的界面

public interface Interface1 {
    Object Execute(String commandToExecute) throws Exception;
}

然后我试图模拟它以便我可以测试将调用它的类的行为:

which then I 'm trying to mock so I can test the behaviour of the class that will call it:

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

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

But the compiler tells me that there is an unhandled exception. The definition of the Retrieve method is:

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

mockito 文档只展示了 RuntimeException 的使用,我在 StackOverflow 上没有看到类似的东西.我使用的是 Java 1.7u25 和 mockito 1.9.5

The mockito documentation only shows uses of RuntimeException, and I have not seen anything on similar on StackOverflow. I'm using Java 1.7u25 and mockito 1.9.5

推荐答案

假设你的测试方法没有声明它抛出 Exception,编译器是绝对正确的.这一行:

Assuming your test method doesn't declare that it throws Exception, the compiler's absolutely right. This line:

when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());

... 对 Interface1 的实例调用 Execute.那可能会抛出Exception,所以你要么需要捕获它,要么声明你的方法抛出它.

... calls Execute on an instance of Interface1. That can throw Exception, so you either need to catch it or declare that your method throws it.

我个人建议只声明测试方法抛出Exception.没有其他人会关心那个声明,你真的不想抓住它.

I would personally recommend just declaring that the test method throws Exception. Nothing else will care about that declaration, and you really don't want to catch it.

这篇关于尝试使用 mockito 抛出检查异常的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆