Mockito.spy() should be used with doReturn() instead of thenReturn()

Let me just copy the official documentation


        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);
      

Don’t ask why !

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.