使用 Mockito 从模拟中抛出已检查的异常

2022-01-08 00:00:00 mocking mockito java

我试图让我的一个模拟对象在调用特定方法时抛出一个检查异常.我正在尝试以下方法.

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从一个mock对象中抛出checked Exceptions吗?

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

推荐答案

检查 列表.
get(int index) 方法被声明为仅抛出扩展 RuntimeExceptionIndexOutOfBoundException.
您正试图告诉 Mockito 抛出一个异常 SomeException(),该异常 该特定方法调用无法抛出该异常.

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

进一步澄清.
List 接口不提供从 get(int index) 方法抛出一个经过检查的异常,这就是 Mockito 失败的原因.当您创建 mocked List 时,Mockito 将使用 List 的定义.class 来创建它的 mock.

To clarify further.
The List interface does not provide for a checked Exception to be thrown from the get(int index) method and that is why Mockito is failing.
When you create the mocked List, Mockito will use the definition of List.class to creates its mock.

您使用 when(list.get(0)).thenThrow(new SomeException()) 指定的行为 与 List API 中的方法签名不匹配,因为 get(int index) 方法不会抛出 SomeException() 所以 Mockito 失败.

The behavior you are specifying with the when(list.get(0)).thenThrow(new SomeException()) doesn't match the method signature in List API, because get(int index) method does not throw SomeException() so Mockito fails.

如果你真的想这样做,那么让 Mockito 抛出一个 new RuntimeException() 甚至更好地抛出一个 new ArrayIndexOutOfBoundsException() 因为 API 指定这是要抛出的唯一有效异常.

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.

相关文章