This code from the documentation完全让我困惑:
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://mockito.github.io/mockito/docs/current/org/mockito/Mockito.html#13
当然,每个后续调用都会返回模拟结果。
如果您不希望调用真正的方法(例如 when(spy.get(0)).thenReturn(...)
可能会抛出 IndexOutOfBoundsException
code>,您必须使用此模式:doReturn(...).when(spy).get(0);
关于java - Mockito spy 如何知道它何时进行 spy Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26920198/