Video in progress
When working with a spy, why does the following stubbing give an unexpected result, and how do you fix it?
List<String> list = spy(new ArrayList<>());
when(list.get(0)).thenReturn("salom");
System.out.println(list.get(0));
When you write when(spy.get(0)), get(0) is called on the real list, and an empty list throws IndexOutOfBoundsException. For a spy you have to write doReturn("x").when(spy).get(0), which doesn't call the real method.
📖 Answer
On a mock, when(mock.method()) is safe, because a mock method does nothing. A spy is a real object: for the argument of when(...) to be evaluated, Java first calls list.get(0), and that is the real ArrayList.get, which fails on an empty list. The test stops with an IndexOutOfBoundsException on the stubbing line itself.
The correct version:
List<String> list = spy(new ArrayList<>());
doReturn("salom").when(list).get(0); // the real get is not called
System.out.println(list.get(0)); // salom
The doReturn/doThrow/doAnswer/doNothing family is also needed in two other places:
- stubbing
voidmethods:doThrow(new IOException()).when(writer).flush();becausewhen(writer.flush())won't compile; - when the real method is expensive or has side effects (writes to the database, sends an email).
Some teams use the doReturn style everywhere to avoid confusion, but it gives up type checking: doReturn(42).when(list).get(0) compiles and only fails when it runs.
Sign up to mark studied questions and save your progress.