0
0
JUnittesting~10 mins

Choosing the right test double in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test verifies that a service correctly uses a mock dependency to return expected data. It checks that the mock is called and the service returns the mocked value.

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

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

interface DataFetcher {
    String fetchData();
}

class DataService {
    private final DataFetcher fetcher;

    DataService(DataFetcher fetcher) {
        this.fetcher = fetcher;
    }

    String getData() {
        return fetcher.fetchData();
    }
}

public class DataServiceTest {
    private DataFetcher fetcherMock;
    private DataService service;

    @BeforeEach
    void setup() {
        fetcherMock = mock(DataFetcher.class);
        service = new DataService(fetcherMock);
    }

    @Test
    void testGetDataReturnsMockedValue() {
        when(fetcherMock.fetchData()).thenReturn("mocked data");

        String result = service.getData();

        verify(fetcherMock).fetchData();
        assertEquals("mocked data", result);
    }
}
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initializes test class-PASS
2Creates mock of DataFetcher interface using Mockito.mock()fetcherMock is a mock object that can simulate DataFetcher-PASS
3Creates DataService instance with fetcherMock injectedservice uses fetcherMock as its dependency-PASS
4Sets up mock behavior: fetcherMock.fetchData() returns 'mocked data'fetcherMock is programmed to return 'mocked data' when fetchData() is called-PASS
5Calls service.getData() which calls fetcherMock.fetchData()fetcherMock.fetchData() is invoked-PASS
6Verifies fetcherMock.fetchData() was called exactly onceMockito verifies interaction with mockfetcherMock.fetchData() was called oncePASS
7Asserts that service.getData() returned 'mocked data'Result string is 'mocked data'assertEquals('mocked data', result)PASS
8Test ends successfullyAll assertions passed, no exceptions thrown-PASS
Failure Scenario
Failing Condition: The mock was not set up to return the expected value or fetchData() was not called
Execution Trace Quiz - 3 Questions
Test your understanding
What is the purpose of using a mock in this test?
ATo replace the DataService with a fake
BTo simulate the DataFetcher dependency and control its behavior
CTo test the real DataFetcher implementation
DTo check the database connection
Key Result
Use mocks to isolate the unit under test by simulating dependencies. Always verify that mocks are called as expected to ensure correct interaction.