使用Mockito时嘲讽和间谍有什么区别? [英] What is the difference between mocking and spying when using Mockito?

查看:128
本文介绍了使用Mockito时嘲讽和间谍有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Mockito间谍会有什么用例?



在我看来,使用callRealMethod可以使用mock处理每个间谍用例。



我可以看到的一个区别是,如果你想让大多数方法调用都是真实的,它会节省一些代码行来使用模拟和间谍。这是它还是我错过了更大的图片?

解决方案

答案在文档


真正的部分嘲讽(自1.8.0开始)



最后,在经过多次内部辩论后,在邮件列表上的讨论中,Mockito增加了部分模拟支持。以前我们认为部分模拟是代码味道。但是,我们发现了部分模拟的合法用例 - 更多阅读:这里



在发布之前,1.8 spy()并没有产生真正的部分嘲讽,而且对于一些用户而言令人困惑。

b $ b $ c> spy(),但当然留下间谍(),以确保向后兼容。



否则,你是对的:间谍的所有方法都是真实的除非残留。除非调用 callRealMethod(),否则模拟的所有方法都是存根的。一般来说,我更喜欢使用 callRealMethod(),因为它不会强迫我使用 doXxx()。when()成语而不是传统的 when()。thenXxx()


What would be a use case for a use of a Mockito spy?

It seems to me that every spy use case can be handled with a mock, using callRealMethod.

One difference I can see is if you want most method calls to be real, it saves some lines of code to use a mock vs. a spy. Is that it or am I missing the bigger picture?

解决方案

The answer is in the documentation:

Real partial mocks (Since 1.8.0)

Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito. Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks - more reading: here

Before release 1.8 spy() was not producing real partial mocks and it was confusing for some users.

callRealMethod() was introduced after spy(), but spy() was left there of course, to ensure backward compatibility.

Otherwise, you're right: all the methods of a spy are real unless stubbed. All the methods of a mock are stubbed unless callRealMethod() is called. In general, I would prefer using callRealMethod(), because it doesn't force me to use the doXxx().when() idiom instead of the traditional when().thenXxx()

这篇关于使用Mockito时嘲讽和间谍有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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