0
0
JUnittesting~10 mins

doReturn and doThrow in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test demonstrates how to use doReturn to mock a method's return value and doThrow to simulate an exception in JUnit with Mockito. It verifies correct behavior when the mocked method returns a value and when it throws an exception.

Test Code - JUnit with Mockito
JUnit
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

class Service {
    String fetchData() {
        return "real data";
    }
}

public class DoReturnDoThrowTest {

    @Test
    void testDoReturnAndDoThrow() {
        Service mockService = Mockito.mock(Service.class);

        // Use doReturn to mock fetchData to return "mocked data"
        doReturn("mocked data").when(mockService).fetchData();
        String result = mockService.fetchData();
        assertEquals("mocked data", result);

        // Use doThrow to mock fetchData to throw RuntimeException
        doThrow(new RuntimeException("Error occurred")).when(mockService).fetchData();
        RuntimeException thrown = assertThrows(RuntimeException.class, () -> {
            mockService.fetchData();
        });
        assertEquals("Error occurred", thrown.getMessage());
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2Mockito creates mock object of Service classmockService is a mock instance of Service-PASS
3doReturn("mocked data") set up for mockService.fetchData()fetchData() will return "mocked data" when called-PASS
4Call mockService.fetchData()fetchData() returns "mocked data"assertEquals("mocked data", result)PASS
5doThrow(RuntimeException) set up for mockService.fetchData()fetchData() will throw RuntimeException when called-PASS
6Call mockService.fetchData() expecting exceptionfetchData() throws RuntimeException with message "Error occurred"assertThrows(RuntimeException.class, ...), assertEquals("Error occurred", thrown.getMessage())PASS
7Test endsAll assertions passed-PASS
Failure Scenario
Failing Condition: If doReturn or doThrow is not set up correctly, fetchData() returns null or does not throw exception
Execution Trace Quiz - 3 Questions
Test your understanding
What does doReturn("mocked data").when(mockService).fetchData() do?
AIt makes fetchData() return "mocked data" when called
BIt throws an exception when fetchData() is called
CIt calls the real fetchData() method
DIt disables fetchData() method
Key Result
Use doReturn() to safely mock methods especially on spy objects to avoid calling real methods, and use doThrow() to simulate exceptions for robust negative testing.