This code from the documentation is totally baffling me:
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");
I get it, Mockito is weird and hardly still in Java. Confusing thing is spy.*
has to evaluate fully before it knows whether it's wrapped in a when()
or something. How on earth would the first spy.*
method not call on the real object but the later ones doe?
I don't know the exact implementation, but I can take a guess.
The call to
spy(...)
first proxies the given object and keeps it as a reference to delegate calls.The call
is practically equivalent to
The first call to
size()
is invoked on the proxy. Internally, it can register the call, pushing it, for example, on astatic
(global) Mockito stack. When you then invokewhen()
, Mockito pops from the stack, recognizes the call tosize()
as needing stubbing and performs whatever logic required to do so.This can explain why stubbing in a multithreaded environment is bad business.