使用Mockito模拟异常

本文介绍了如何使用Mockito库在单元测试中模拟方法抛出异常。针对方法返回非void和void的情况,分别展示了when().thenThrow()和doThrow()的用法。此外,还讲解了如何模拟具体的异常对象。无论是Mock对象还是Spy对象,模拟异常的方式基本一致,有助于在测试中更好地验证异常处理逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


使用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");
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值