doReturn(), doThrow(), and doAnswer() are Mockito's alternative stubbing syntax, used when when()...then...() doesn't apply cleanly, such as for void methods or spies.
On a spy over a real ArrayList, doReturn(999).when(spyList).size() overrides size() without triggering any real list logic during stubbing.
List<String> spyList = spy(new ArrayList<>());
doReturn(999).when(spyList).size();
doAnswer(invocation -> {
String arg = invocation.getArgument(0);
return arg.toUpperCase();
}).when(mockService).transform(anyString());A concise interview answer is
doReturn(), doThrow(), and doAnswer() are the do-family stubbing methods I use for void calls, spies, or when I need dynamic behavior based on the arguments passed in. doReturn() avoids invoking the real method on a spy, and doAnswer() gives full control to compute a result or trigger a side effect.
Last updated: 16 July 2026
Previous question: How do you mock a method that returns void in Mockito?
Next question: How do you verify the behavior of a mock object in Mockito?