Mocking Exception Throwing using Mockito – 使用Mockito嘲弄异常抛出

最后修改: 2017年 10月 8日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’ll focus on how to configure a method call to throw an exception with Mockito.

在这个快速教程中,我们将重点介绍如何用Mockito配置一个方法调用来抛出一个异常。

For more information on the library, also check out our Mockito series.

有关该库的更多信息,还可以查看我们的Mockito系列

Here’s the simple dictionary class that we’ll use:

这里是我们要使用的简单的字典类。

class MyDictionary {
    private Map<String, String> wordMap = new HashMap<>();

    public void add(String word, String meaning) {
        wordMap.put(word, meaning);
    }

    public String getMeaning(String word) {
        return wordMap.get(word);
    }
}

2. Non-Void Return Type

2.非Void返回类型

First, if our method return type is not void, we can use when().thenThrow():

首先,如果我们的方法返回类型不是void,我们可以使用when().thenThrow()

@Test(expected = NullPointerException.class)
public void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
    MyDictionary dictMock = mock(MyDictionary.class);
    when(dictMock.getMeaning(anyString()))
      .thenThrow(NullPointerException.class);

    dictMock.getMeaning("word");
}

Notice that we configured the getMeaning() method — which returns a value of type String — to throw a NullPointerException when called.

请注意,我们配置了getMeaning()方法–它返回一个String类型的值–在调用时抛出一个NullPointerException

3. Void Return Type

3.Void返回类型

Now, if our method returns void, we’ll use doThrow():

现在,如果我们的方法返回void,,我们将使用doThrow()

@Test(expected = IllegalStateException.class)
public void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() {
    MyDictionary dictMock = mock(MyDictionary.class);
    doThrow(IllegalStateException.class)
      .when(dictMock)
      .add(anyString(), anyString());

    dictMock.add("word", "meaning");
}

Here, we configured an add() method — which returns void — to throw IllegalStateException when called.

在这里,我们配置了一个add()方法–它返回void–在调用时抛出IllegalStateException

We can’t use when().thenThrow() with void return type, as the compiler doesn’t allow void methods inside brackets.

我们不能使用when().thenThrow()void返回类型,因为编译器不允许括号内的void方法。

4. Exception as an Object

4.作为一个对象的异常

To configure the exception itself, we can pass the exception’s class as in our previous examples or as an object:

为了配置异常本身,我们可以像前面的例子一样传递异常的类,或者作为一个对象。

@Test(expected = NullPointerException.class)
public void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
    MyDictionary dictMock = mock(MyDictionary.class);
    when(dictMock.getMeaning(anyString()))
      .thenThrow(new NullPointerException("Error occurred"));

    dictMock.getMeaning("word");
}

And we can do the same with doThrow():

我们也可以用 doThrow()做同样的事情。

@Test(expected = IllegalStateException.class)
public void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
    MyDictionary dictMock = mock(MyDictionary.class);
    doThrow(new IllegalStateException("Error occurred"))
      .when(dictMock)
      .add(anyString(), anyString());

    dictMock.add("word", "meaning");
}

5. Spy

5 间谍

We can also configure Spy to throw an exception the same way we did with the mock:

我们还可以配置Spy来抛出一个异常,就像我们对mock所做的一样。

@Test(expected = NullPointerException.class)
public void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
    MyDictionary dict = new MyDictionary();
    MyDictionary spy = Mockito.spy(dict);
    when(spy.getMeaning(anyString()))
      .thenThrow(NullPointerException.class);

    spy.getMeaning("word");
}

6. Conclusion

6.结论

In this article, we explored how to configure method calls to throw an exception in Mockito.

在这篇文章中,我们探讨了如何在Mockito中配置方法调用来抛出一个异常。

As always, the full source code can be found over on GitHub.

一如既往,完整的源代码可以在GitHub上找到over