Mockito测试void方法会引发异常

本文翻译自:Mockito test a void method throws an exception

I have a method with a void return type. 我有一个void返回类型的方法。 It can also throw a number of exceptions so I'd like to test those exceptions being thrown. 它还可以引发许多异常,因此我想测试所引发的异常。 All attempts have failed with the same reason: 所有尝试均以相同的原因失败:

The method when(T) in the type Stubber is not applicable for the arguments (void) Stubber类型中的when(T)方法不适用于参数(void)

Any ideas how I can get the method to throw a specified exception? 有什么想法可以获取引发指定异常的方法吗?

doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));

#1楼

参考:https://stackoom.com/question/11azR/Mockito测试void方法会引发异常


#2楼

The parentheses are badly placed. 括号放置不正确。 You must use 您必须使用

doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
                                          ^

and not 并不是

doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
                                                                   ^

This is explained in the documentation 文档中对此进行了解释


#3楼

If you ever wondered how to do it using the new BDD style of Mockito: 如果您想知道如何使用新的BDD样式的Mockito来做到这一点:

willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));

And for future reference one may need to throw exception and then do nothing: 为了将来参考,可能需要抛出异常,然后什么也不做:

willThrow(new Exception()).willNothing().given(mockedObject).methodReturningVoid(...));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值