使用 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 时,模拟和间谍有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何模拟超级参考(在超级类上)?How to mock super reference (on super class)?(如何模拟超级参考(在超级类上)?)
Java 模拟数据库连接Java mock database connection(Java 模拟数据库连接)
Mockito ClassCastException - 无法投射模拟Mockito ClassCastException - A mock cannot be cast(Mockito ClassCastException - 无法投射模拟)
将值设置为模拟对象但获取 nullSet value to mocked object but get null(将值设置为模拟对象但获取 null)
如何模拟 DriverManager.getConnection(...)?How to mock DriverManager.getConnection(...)?(如何模拟 DriverManager.getConnection(...)?)
模拟;使用列表调用验证方法,忽略列表中元素的Mockito; verify method was called with list, ignore order of elements in list(模拟;使用列表调用验证方法,忽略列表中元素的顺序)