Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

This spy test fails with an exception from the real method:

Java
List<String> spy = spy(new ArrayList<>());
when(spy.get(0)).thenReturn("x");

Why, and how do you fix it?

when(spy.get(0)) is ordinary Java: the argument spy.get(0) is evaluated first, and on a spy that runs the real ArrayList.get(0) on an empty list, which throws IndexOutOfBoundsException before when() is even called. The fix is doReturn("x").when(spy).get(0), which tells Mockito what to return before the call and then records the call without running the real method. The same doXxx() form is needed for void methods and for any spied method with side effects, and needing many of these stubs is often a sign that the class does too much.

Why this question is asked

This test is a small trap that almost everyone meets once. The same when(...).thenReturn(...) line works perfectly on a mock, so it is natural to expect it to work on a spy. Interviewers ask about it because the explanation requires understanding both how a spy works and how Java evaluates the stubbing line, and because the fix generalises to void methods and side effects. In this answer, we will reproduce the failure, follow the line step by step to see exactly where it throws, apply the fix and see why it works, extend it to void methods, and finish with what frequent spying says about the design.

1A Quick Recap of Spies

A spy is a wrapper around a real object. Mockito creates it by copying the real object's state into a generated subclass. Every call on the spy goes to the real method, unless we have stubbed that method, and every call is recorded so we can verify it later. That is the difference from a mock, whose unstubbed methods do nothing and return defaults such as null, 0 or false.

2Reproducing the Failure

Here is the test from the question, with the output.

Java
@Test
void stubsGet() {
List<String> spy = spy(new ArrayList<>());
when(spy.get(0)).thenReturn("x");
assertEquals("x", spy.get(0));
}
// java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
// at java.base/java.util.ArrayList.get(ArrayList.java:...)
// at ...
// at StubsGetTest.stubsGet(StubsGetTest.java:4) <- the when(...) line

Notice which line fails: the stubbing line, not the assertion. The test never gets as far as checking anything.

3Why the Real Method Runs

The key is the order in which Java evaluates when(spy.get(0)). when() is a normal static method, and Java evaluates a method's arguments before calling it. So the first thing that happens is the call spy.get(0). Mockito sees the call, finds no stub for get(0) yet, and does what a spy does with an unstubbed method: it calls the real ArrayList.get(0). The list is empty, so the real method throws IndexOutOfBoundsException. when() is never reached.

On a mock, the same line works because the unstubbed get(0) returns null instead of running real code. Mockito remembers that get(0) was the last call, when(null) then picks up that remembered call, and thenReturn("x") attaches the answer to it. The trick relies on the call in the argument being harmless, and on a spy it is not.

Step throughEvaluating when(spy.get(0)) on a spy
TestSpyReal ArrayList
spy.get(0) (argument of when, runs first)
no stub for get(0) yet
call the real get(0)
throws IndexOutOfBoundsException
when(...) is never called

5 messages in order. Play them, or step through them one at a time.

The exception happens while Java is still evaluating the argument of when().

4The Fix: doReturn().when()

Mockito's doXxx() family turns the stubbing around. We name the answer first, then tell Mockito which object to watch, and only then make the call. When the call happens, Mockito is already in stubbing mode, so it records the call as the target of the stub and does not run the real method.

Java
@Test
void stubsGet() {
List<String> spy = spy(new ArrayList<>());
doReturn("x").when(spy).get(0); // the real get(0) is not called
assertEquals("x", spy.get(0)); // passes: "x"
assertEquals(0, spy.size()); // passes: other methods are still real
}

Notice the different shape. when(spy) returns the spy itself in stubbing mode, and .get(0) on that is the call being stubbed. Because the real method never runs, it does not matter that the list is empty. The last line shows that the spy is still a spy: size() was not stubbed, so the real method reports 0.

5The Same Rule for Void Methods and Side Effects

The when(...) form cannot be used for void methods at all, because a void call cannot be an argument: when(spy.clear()) does not compile. And for spies, any method with side effects has the same problem as get(0), because the real method runs during stubbing. Sending an email, writing to a database or incrementing a counter would all happen once while we are only trying to set up the test.

Java
class Notifier {
void send(String to) { smtp.deliver(to); } // real side effect
int sentToday() { return counter.incrementAndGet(); } // changes state when called
}
Notifier spy = spy(new Notifier(smtp));
doNothing().when(spy).send(anyString()); // void method, real send() never runs
doThrow(new IllegalStateException("down")).when(spy).send("ops@acme.com");
doReturn(5).when(spy).sentToday(); // counter not incremented during setup
// The wrong form would deliver an email or bump the counter during setup:
// when(spy.sentToday()).thenReturn(5); // runs the real sentToday() once

So the simple rule for spies is: always stub with doReturn, doNothing, doThrow or doAnswer. The when(...).thenReturn(...) form is fine for mocks, but not for spies.

6What Frequent Spying Tells Us About the Design

Spies have legitimate uses, such as wrapping legacy code that cannot be refactored yet, or observing a real object in a test. But if many tests spy on the class under test and stub some of its own methods, that usually means the class does too much: the parts we keep replacing are really separate responsibilities. Moving them into their own collaborators, injected through the constructor, lets us replace them with ordinary mocks or fakes, and the awkward partial stubbing disappears. Mockito's own documentation warns that partial mocks are a sign of code smell in new code for this reason.

7Follow-up questions

Does doReturn() check the return type at compile time?

No. doReturn takes an Object, so doReturn(42).when(spy).get(0) compiles and fails at run time with a WrongTypeOfReturnValue error. when(...).thenReturn(...) is type-checked, which is why it remains the preferred form for mocks.

Is there a way to make when() safe for spies?

Only by making the real call harmless, for example by adding an element to the list before stubbing. That is fragile and hides the intent. doReturn is the intended solution, and it is the form Mockito recommends for spies.

8Conclusion

In this answer, we saw that when(spy.get(0)) fails because Java evaluates spy.get(0) before calling when(), and on a spy that runs the real ArrayList.get(0), which throws on an empty list. doReturn("x").when(spy).get(0) puts Mockito into stubbing mode before the call, so the real method never runs. The same doXxx() forms are needed for void methods and for spied methods with side effects, and frequent partial stubbing of the class under test is a sign that it should be split into collaborators.

What to say in the interviewAbout 80 seconds aloud

Open with

The problem is the order of evaluation. when(spy.get(0)) is a normal method call, so Java first evaluates its argument, spy.get(0). On a mock that is harmless, because an unstubbed method returns null, and Mockito then attaches thenReturn to the last call it saw.

Then, if they want more

But on a spy, an unstubbed method calls the real method. So the real ArrayList.get(0) runs on an empty list and throws IndexOutOfBoundsException, and when() is never reached. The stack trace points at the stubbing line, not at the assertion. The fix is the doReturn form: doReturn("x").when(spy).get(0).

Here Mockito knows the answer first, when(spy) returns the spy in stubbing mode, and the get(0) call on it is recorded as the method to stub without running the real code. Other methods on the spy stay real, so size() still returns 0.

The same applies to void methods, where I use doNothing or doThrow, and to any spied method with side effects, because with when() the real side effect would happen once during setup. So for spies I always use the do-family.

And if I find myself stubbing many methods of the class under test, I take it as a hint that the class does too much and should be split into collaborators I can mock normally.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "This spy test fails with an exception from the real method:": https://scrivio-interview-library.netlify.app/java/mocking/841d93840a/