使用 Mockito 时,模拟和间谍有什么区别?

What is the difference between mocking and spying when using Mockito?(使用 Mockito 时,模拟和间谍有什么区别?)
本文介绍了使用 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 时,模拟和间谍有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)