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.
0
0
doReturn and doThrow in JUnit
Introduction
When you want a mocked method to return a specific value without calling the real method.
When you want to simulate an exception being thrown by a mocked method.
When the method you mock is final or on a spy and cannot be stubbed with usual <code>when().thenReturn()</code> syntax.
When testing error handling by forcing exceptions from dependencies.
Syntax
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.
Examples
This makes
mockedList.get(0) return "Hello".JUnit
doReturn("Hello").when(mockedList).get(0);
This makes
mockedList.clear() throw a RuntimeException.JUnit
doThrow(new RuntimeException()).when(mockedList).clear();
Sample Program
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.
JUnit
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()); } }
OutputSuccess
Important Notes
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.
Summary
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.