doReturn and doThrow in JUnit - Build an Automation Script
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class ServiceTest { @Mock Dependency dependency; @InjectMocks Service service; @Test void testDoReturn() { // Arrange doReturn("mocked response").when(dependency).getData(); // Act String result = service.processData(); // Assert assertEquals("mocked response", result); } @Test void testDoThrow() { // Arrange doThrow(new RuntimeException("mocked exception")).when(dependency).getData(); // Act & Assert RuntimeException thrown = assertThrows(RuntimeException.class, () -> { service.processData(); }); assertEquals("mocked exception", thrown.getMessage()); } } // Supporting classes class Service { private final Dependency dependency; public Service(Dependency dependency) { this.dependency = dependency; } public String processData() { return dependency.getData(); } } interface Dependency { String getData(); }
This test class uses JUnit 5 and Mockito to automate the manual test case steps.
Annotations: @ExtendWith(MockitoExtension.class) enables Mockito support. @Mock creates a mock for the dependency. @InjectMocks injects the mock into the service.
testDoReturn: Uses doReturn to mock dependency.getData() to return "mocked response". Then calls service.processData() and asserts the returned value matches.
testDoThrow: Uses doThrow to mock dependency.getData() to throw a RuntimeException. Then asserts that calling service.processData() throws the expected exception with the correct message.
This approach clearly separates setup, action, and verification steps, making the test easy to read and maintain.
Now add data-driven testing with 3 different return values and 3 different exceptions for the mocked method