问题描述
doThrow()
和thenThrow()
有什么区别?
比方说,我们要模拟身份验证服务以验证用户的登录凭据.如果我们要模拟一个异常,那么以下两行有什么区别?
Let's say, we want to mock an authentication service to validate the login credentials of a user. What's the difference between the following two lines if we were to mock an exception?
doThrow(new BadCredentialsException("Wrong username/password!")).when(authenticationService).login("user1", "pass1");
vs
when(authenticationService.login("user1", "pass1")).thenThrow(new BadCredentialsException("Wrong username/password!"));
推荐答案
几乎没有:在简单情况下,它们的行为完全相同. when
语法读起来更像是英语中的语法句子.
Almost nothing: in simple cases they behave exactly the same. The when
syntax reads more like a grammatical sentence in English.
为什么差不多"?请注意,when
样式实际上包含对authenticationService.login
的调用.那是该行中评估的第一个表达式,因此,在调用when
的过程中,无论发生任何行为,都会发生.大多数时候,这里没有问题:方法调用没有存根行为,因此Mockito仅返回一个虚拟值,并且这两个调用完全相同.但是,如果满足以下任一条件,则可能不是这种情况:
Why "almost"? Note that the when
style actually contains a call to authenticationService.login
. That's the first expression evaluated in that line, so whatever behavior you have stubbed will happen during the call to when
. Most of the time, there's no problem here: the method call has no stubbed behavior, so Mockito only returns a dummy value and the two calls are exactly equivalent. However, this might not be the case if either of the following are true:
- 您正在改写已经打断的行为,特别是运行答案"或引发异常
- 您正在与间谍一起实施非平凡的实现
在这种情况下,doThrow
将调用when(authenticationService)
并停用所有危险行为,而when().thenThrow()
将调用危险方法并退出测试.
In those cases, doThrow
will call when(authenticationService)
and deactivate all dangerous behavior, whereas when().thenThrow()
will invoke the dangerous method and throw off your test.
(当然,对于void方法,您还需要使用doThrow
-when
语法只有在没有返回值的情况下才能编译.那里没有选择.)
(Of course, for void methods, you'll also need to use doThrow
—the when
syntax won't compile without a return value. There's no choice there.)
因此,doThrow
通常总是更安全一些,但是when().thenThrow()
更具可读性,并且通常等效.
Thus, doThrow
is always a little safer as a rule, but when().thenThrow()
is slightly more readable and usually equivalent.
这篇关于Mockito:doThrow()和thenThrow()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!