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

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

问题描述

使用 Mockito 间谍的用例是什么?

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

在我看来,每个间谍用例都可以通过模拟处理,使用 callRealMethod.

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?

推荐答案

答案在文档:

真正的部分模拟(自 1.8.0 起)

Real partial mocks (Since 1.8.0)

最后,经过多次内部辩论&邮件列表上的讨论,部分模拟支持已添加到 Mockito.以前我们将部分模拟视为代码异味.但是,我们发现了部分模拟的合法用例.

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.

在 1.8 版之前,spy() 没有产生真正的部分模拟,这让一些用户感到困惑.阅读更多关于间谍的信息:这里 或在 javadoc 中用于 spy(Object) 方法.

Before release 1.8 spy() was not producing real partial mocks and it was confusing for some users. Read more about spying: here or in javadoc for spy(Object) method.

callRealMethod() 是在 spy() 之后引入的,但 spy() 当然是留在那里,以确保向后兼容.

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

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

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天全站免登陆