抛出与Mockito模拟的例外情况 [英] throw checked Exceptions from mocks with Mockito

查看:134
本文介绍了抛出与Mockito模拟的例外情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让我的一个模拟对象在调用特定方法时抛出一个已检查的Exception。我正在尝试以下方法。

I'm trying to have one of my mocked objects throw a checked Exception when a particular method is called. I'm trying the following.

@Test(expectedExceptions = SomeException.class)
public void throwCheckedException() {
    List<String> list = mock(List.class);
    when(list.get(0)).thenThrow(new SomeException());
    String test = list.get(0);
}

public class SomeException extends Exception {
}

然而,这会产生以下错误。

However, that produces the following error.

org.testng.TestException: 
Expected exception com.testing.MockitoCheckedExceptions$SomeException but got org.mockito.exceptions.base.MockitoException: 
Checked exception is invalid for this method!
Invalid: com.testing.MockitoCheckedExceptions$SomeException

查看 Mockito文档,他们只使用 RuntimeException ,是否无法使用Mockito从模拟对象中抛出已检查的异常?

Looking at the Mockito documentation, they only use RuntimeException, is it not possible to throw checked Exceptions from a mock object with Mockito?

推荐答案

检查用于列表的Java API。声明get(int)方法只抛出IndexOutOfBoundException,它扩展了RuntimeException。您试图告诉Mockito抛出一个异常,该异常无法通过该特定方法调用抛出。

Check the Java API for List. The get(int) method is declared to throw only the IndexOutOfBoundException which extends RuntimeException. You are trying to tell Mockito to a throw an exception that is not valid to be thrown by that particular method call.

进一步澄清。 List接口不提供从get()方法抛出的已检查异常,这就是Mockito失败的原因。当您创建模拟List时,Mockito使用List.class的定义来创建其模拟。您使用指定的行为(list.get(0))。thenThrow(new SomeException())与List.class中的方法签名不匹配,因此Mockito失败了。如果你真的想这样做,那么让Mockito抛出一个 new RunTimeException(),甚至更好地抛出一个 new ArrayIndexOutOfBoundsException()因为API指定这是唯一有效的抛出异常。

To clarify further. The List interface does not provide for a checked Exception to be thrown from the get() method and that is why Mockito is failing. When you create the mocked List, Mockito using the definition of List.class to creates its mock. The behavior you are specifying with the when(list.get(0)).thenThrow(new SomeException()) doesn't match the method signature in List.class, so Mockito fails. If you really want to do this, then have Mockito throw a new RunTimeException() or even better throw a new ArrayIndexOutOfBoundsException() since the API specifies that that is the only valid Exception to be thrown.

这篇关于抛出与Mockito模拟的例外情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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