[英]Mockito spy - when calling inner class method not spying method in spy object
[英]How does a Mockito spy know when it is spying?
文檔中的這段代碼讓我很困惑:
List list = new LinkedList();
List spy = spy(list);
when(spy.size()).thenReturn(100); // <--- how does this spy know
// not to call the real method????
//using the spy calls *real* methods
spy.add("one");
spy.add("two");
我明白了,Mockito很奇怪,而且幾乎不使用Java。 令人困惑的事情是spy.*
必須先進行全面評估,然后才能知道它是否包裝在when()
或其他內容中。 到底第一個spy.*
方法不會調用真實對象,而隨后的對象會如何調用呢?
根據文檔,第一個when(spy.size()).thenReturn(100)
實際上會調用真正的List.size()
方法,請參見: http : List.size()
/mockito/Mockito.html#13
然后,每次后續調用都將返回模擬結果。
如果您不希望調用真實方法(例如, when(spy.get(0)).thenReturn(...)
可能會拋出IndexOutOfBoundsException
,則必須使用以下模式: doReturn(...).when(spy).get(0);
我不知道確切的實現方式,但我可以猜測。
對spy(...)
的調用首先代理給定對象,並將其保留為對委托調用的引用。
通話
when(spy.size()).thenReturn(100);
實際上相當於
Integer result = spy.size();
OngoingStubbing<Integer> stubbing = when(result); // result is useless
stubbing.thenReturn(100);
對size()
的第一次調用是在代理上調用的。 在內部,它可以注冊呼叫,例如在static
(全局)Mockito堆棧上推送該呼叫。 然后,當您調用when()
,Mockito從堆棧中彈出,將對size()
的調用識別為需要存根,並執行所需的任何邏輯。
這可以解釋為什么在多線程環境中進行存根是不好的生意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.