使用Mockito模拟异常

接下来我们将以MyDictionary类为例进行介绍

class MyDictionary {

    private Map<String, String> wordMap;

    MyDictionary() {
        wordMap = new HashMap<>();
    }

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

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

1 Mock对象模拟异常

1.1 方法返回类型非void

如果方法的返回类型非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");
    }

1.2 方法返回类型是void

如果方法返回类型是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");
}

1.3 模拟异常对象

我们不仅可以在thenThrow()或者doThrow() 中模拟异常类,还可以模拟异常对象。

    @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");
    }

    @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");
    }

2 Spy对象模拟异常

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");
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,803评论 1 32
  • 几点说明:代码中的 //<== 表示跟上面的相比,这是新增的,或者是修改的代码,不知道怎么样在代码块里面再强调几行...
    邹小创阅读 14,774评论 15 41
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 13,871评论 6 13
  • 这几天被即将的期末考试折磨到没脾气。考试未至,思维却已混乱。作为新生,对未知的大学考试制度和出题模式实在惶恐。...
    木兮zz阅读 656评论 0 0
  • 这里对么
    这没阅读 861评论 0 0