We use doReturn and doThrow to control what a mocked method does during tests. This helps us check how our code behaves with different responses or errors.
doReturn and doThrow in JUnit
doReturn(value).when(mockObject).methodCall(); doThrow(exception).when(mockObject).methodCall();
doReturn sets a return value for a method call on a mock.
doThrow makes the method throw an exception when called.
mockedList.get(0) return "Hello".doReturn("Hello").when(mockedList).get(0);
mockedList.clear() throw a RuntimeException.doThrow(new RuntimeException()).when(mockedList).clear();
This test class shows two tests. The first uses doReturn to make get(0) return a fixed string. The second uses doThrow to make clear() throw an exception. Assertions check the expected results.
import static org.mockito.Mockito.*; import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.*; public class DoReturnDoThrowTest { @Test void testDoReturn() { List<String> mockedList = mock(List.class); doReturn("mocked value").when(mockedList).get(0); String result = mockedList.get(0); assertEquals("mocked value", result); } @Test void testDoThrow() { List<String> mockedList = mock(List.class); doThrow(new IllegalStateException("error")).when(mockedList).clear(); Exception exception = assertThrows(IllegalStateException.class, () -> { mockedList.clear(); }); assertEquals("error", exception.getMessage()); } }
Use doReturn when the method is final or on a spy and cannot be stubbed with when().thenReturn().
doThrow is useful to test how your code handles exceptions from dependencies.
Always verify your mocks behave as expected with assertions.
doReturn sets a return value on a mock method call.
doThrow makes a mock method throw an exception.
Both help test different behaviors without calling real methods.
Practice
doReturn in JUnit mocking?Solution
Step 1: Understand
doReturnusagedoReturnis used to tell a mock what value to return when a specific method is called.Step 2: Differentiate from
doThrowdoThrowmakes the method throw an exception, not return a value.Final Answer:
To specify a value that a mocked method should return when called -> Option AQuick Check:
doReturnsets return value [OK]
- Confusing doReturn with doThrow
- Thinking doReturn verifies method calls
- Assuming doReturn resets mocks
doThrow?Solution
Step 1: Recall correct
The correct syntax isdoThrowsyntaxdoThrow(new ExceptionType()).when(mock).method();to specify the exception and method.Step 2: Check each option
doThrow(new IOException()).when(mockObject).methodName(); matches the correct syntax exactly. Others have misplaced parentheses or wrong order.Final Answer:
doThrow(new IOException()).when(mockObject).methodName(); -> Option CQuick Check:
CorrectdoThrowsyntax = doThrow(new IOException()).when(mockObject).methodName(); [OK]
- Omitting 'new' before exception
- Placing parentheses incorrectly
- Calling method before when()
mockService.getData() is called?
MyService mockService = mock(MyService.class);
doReturn("Hello").when(mockService).getData();
doThrow(new RuntimeException()).when(mockService).getData();
System.out.println(mockService.getData());Solution
Step 1: Analyze the order of stubbing
FirstdoReturn("Hello")is set, thendoThrow(RuntimeException)overrides it for the same method.Step 2: Determine which stub applies on method call
The last stubdoThrowtakes effect, so callinggetData()throws RuntimeException.Final Answer:
RuntimeException is thrown -> Option BQuick Check:
Last stub wins, so exception thrown [OK]
- Assuming first stub applies
- Expecting returned string instead of exception
- Thinking code won't compile
doReturn and doThrow:
doReturn("Success").when(mockService).process();
doThrow(new IllegalArgumentException()).when(mockService).process();
doReturn("Done").when(mockService).process();
String result = mockService.process();Solution
Step 1: Understand stub overriding order
Stubs are applied in order; the last stub for a method is effective.Step 2: Check the last stub
The last stub isdoReturn("Done"), so callingprocess()returns "Done" without exception.Final Answer:
The last doReturn overrides previous stubs, so no error -> Option DQuick Check:
Last stub wins, no exception thrown [OK]
- Thinking doThrow always throws exception regardless of order
- Believing mixing doReturn and doThrow causes compile error
- Expecting exception thrown despite last stub
externalService.fetch(). You want to simulate two calls: the first returns "Data1", the second throws an IOException. Which is the correct way to stub fetch() using doReturn and doThrow?Solution
Step 1: Understand chaining stubs for multiple calls
Mockito allows chaining stubs withdoReturn(...).doThrow(...).when(mock).method();to simulate sequential calls.Step 2: Analyze options
doReturn("Data1").doThrow(new IOException()).when(externalService).fetch();correctly chainsdoReturnthendoThrowfor first return and second throw. SeparatedoReturn("Data1").when(externalService).fetch(); doThrow(new IOException()).when(externalService).fetch();overrides stubs, causing all calls to throw the exception. The other options use repeated returns or incorrect order.Final Answer:
doReturn("Data1").doThrow(new IOException()).when(externalService).fetch(); -> Option AQuick Check:
Chain doReturn then doThrow for sequential calls [OK]
- Overwriting stubs instead of chaining
- Wrong order of doThrow and doReturn
- Expecting multiple when() calls for sequence
Ready to prove it?
Pass the test and this pattern moves unknown
