1

from the doc: Important gotcha on spying real objects!

List list = new LinkedList();
List spy = spy(list);

//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");

//You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);

so, when does when thenReturn not working on spy?

same question here

WesleyHsiung
  • 351
  • 2
  • 13
  • 2
    The documentation of Mockito ( http://static.javadoc.io/org.mockito/mockito-core/2.18.3/org/mockito/Mockito.html ) has the following to say: "Sometimes it's impossible or impractical to use when(Object) for stubbing spies. Therefore for spies it is recommended to always use doReturn|Answer|Throw()|CallRealMethod family of methods for stubbing." The reasons are based on the Mockito internals, but I suggest starting with reading the documentation first, since it explains much. – Florian Schaetz Jun 05 '18 at 18:29
  • I read the documentation,but still don't know when `when thenReturn ` not working? final method?static method? generic parameters? – WesleyHsiung Jun 05 '18 at 22:48
  • so I read the `doReturn `method:[doReturn](http://static.javadoc.io/org.mockito/mockito-core/2.18.3/org/mockito/Mockito.html#doReturn-java.lang.Object-). I think there are three circumstances `when `not working: 1. void method-as doc said,2. real method may throw exception, I tested the this. 3. Overriding a previous exception-stubbing - as doc said. correct me if wrong – WesleyHsiung Jun 05 '18 at 23:12

0 Answers0