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.
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.
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); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initializes test class | - | PASS |
| 2 | Creates mock of DataFetcher interface using Mockito.mock() | fetcherMock is a mock object that can simulate DataFetcher | - | PASS |
| 3 | Creates DataService instance with fetcherMock injected | service uses fetcherMock as its dependency | - | PASS |
| 4 | Sets up mock behavior: fetcherMock.fetchData() returns 'mocked data' | fetcherMock is programmed to return 'mocked data' when fetchData() is called | - | PASS |
| 5 | Calls service.getData() which calls fetcherMock.fetchData() | fetcherMock.fetchData() is invoked | - | PASS |
| 6 | Verifies fetcherMock.fetchData() was called exactly once | Mockito verifies interaction with mock | fetcherMock.fetchData() was called once | PASS |
| 7 | Asserts that service.getData() returned 'mocked data' | Result string is 'mocked data' | assertEquals('mocked data', result) | PASS |
| 8 | Test ends successfully | All assertions passed, no exceptions thrown | - | PASS |