Mockito:doThrow() 和 thenThrow() 之间的区别 [英] Mockito: Difference between doThrow() and thenThrow()

查看:32
本文介绍了Mockito:doThrow() 和 thenThrow() 之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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() 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆