問題描述
使用 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模板網!