0
0
JUnittesting~15 mins

doReturn and doThrow in JUnit - Build an Automation Script

Choose your learning style9 modes available
Test service method behavior using doReturn and doThrow with Mockito
Preconditions (3)
Step 1: Mock the dependency method to return a specific value using doReturn
Step 2: Call the service method that uses the mocked dependency
Step 3: Verify the returned value matches the mocked value
Step 4: Mock the dependency method to throw an exception using doThrow
Step 5: Call the service method that uses the mocked dependency and expect an exception
Step 6: Verify the exception is thrown as expected
✅ Expected Result: The test passes when the service method returns the mocked value and throws the mocked exception as specified
Automation Requirements - JUnit 5 with Mockito
Assertions Needed:
assertEquals to verify returned value
assertThrows to verify exception thrown
Best Practices:
Use @ExtendWith(MockitoExtension.class) for Mockito support
Use doReturn() and doThrow() for mocking void or spy methods
Use descriptive method names for test clarity
Use explicit assertions for expected outcomes
Automated Solution
JUnit
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.

Common Mistakes - 3 Pitfalls
Using when().thenReturn() with spy objects causing real method calls
Not using assertThrows to verify exceptions
Mocking methods without specifying behavior leading to null returns
Bonus Challenge

Now add data-driven testing with 3 different return values and 3 different exceptions for the mocked method

Show Hint