I’m using Mockito to mock service layer methods in my Spring MVC tests. I’ve seen two ways to stub a method:
when(myService.someMethod()).thenReturn(value);
and
doReturn(value).when(myService).someMethod();
They seem to do the same thing, but I read that doReturn() is sometimes preferred. I’m confused about when I should use doReturn() instead of the usual when().thenReturn().
             
            
              
              
              
            
           
          
            
            
              One key difference is that when().thenReturn() actually calls the method when used on a spy or a real object.
This can cause unwanted side effects if the method has logic or throws exceptions.
In contrast, doReturn() does not call the method immediately, so it’s safe for spies or partial mocks:
List<String> list = new ArrayList<>();
List<String> spyList = spy(list);
// This will throw IndexOutOfBoundsException if the list is empty
// when(spyList.get(0)).thenReturn("Hello");
// This works safely
doReturn("Hello").when(spyList).get(0);
So if you’re mocking a spy or an object where calling the real method is risky, use doReturn().
             
            
              
              
              
            
           
          
            
            
              when().thenReturn() cannot be used with void methods because there’s no return value. For void methods, you must use the doNothing(), doThrow(), or doAnswer() variants:
doNothing().when(myService).performAction();
doThrow(new RuntimeException()).when(myService).performAction();
This pattern is consistent with doReturn(), it’s part of Mockito’s “doX().when()” family for safe stubbing.
             
            
              
              
              
            
           
          
            
            
              In some legacy Spring tests, I had services that had initialization logic.
Using when().thenReturn() would sometimes trigger initialization or lazy-loading code unintentionally.
Switching to doReturn() prevented any accidental method execution:
doReturn(mockedValue).when(myService).computeSomething();
It’s a small syntax difference, but doReturn() is more defensive when you don’t want the real method invoked during stubbing.