0
0
JUnittesting~5 mins

Why mocking isolates units under test in JUnit

Choose your learning style9 modes available
Introduction

Mocking helps test one part of code alone by pretending other parts work correctly. This way, you find problems faster and easier.

When testing a method that calls a database, but you don't want to use the real database.
When a function depends on a web service that might be slow or unavailable.
When you want to test a small piece of code without running the whole program.
When you want to check how your code behaves if another part returns specific values or errors.
Syntax
JUnit
import static org.mockito.Mockito.*;

// Create a mock object
MyClass mockObject = mock(MyClass.class);

// Define behavior
when(mockObject.someMethod()).thenReturn(someValue);

// Use mockObject in your test

Use mock() to create a fake version of a class.

Use when(...).thenReturn(...) to tell the mock what to return when a method is called.

Examples
This creates a mock of MyService and makes getData() return "mocked data".
JUnit
MyService mockService = mock(MyService.class);
when(mockService.getData()).thenReturn("mocked data");
This mock returns 10 when getNumber() is called.
JUnit
MyService mockService = mock(MyService.class);
when(mockService.getNumber()).thenReturn(10);
Sample Program

This test uses a mock DataService to provide fixed data. It checks that Calculator sums the numbers correctly without needing a real data source.

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

class Calculator {
    private DataService dataService;

    public Calculator(DataService dataService) {
        this.dataService = dataService;
    }

    public int calculateSum() {
        int[] data = dataService.getData();
        int sum = 0;
        for (int num : data) {
            sum += num;
        }
        return sum;
    }
}

interface DataService {
    int[] getData();
}

public class CalculatorTest {
    @Test
    void testCalculateSum_withMock() {
        DataService mockDataService = mock(DataService.class);
        when(mockDataService.getData()).thenReturn(new int[] {1, 2, 3});

        Calculator calculator = new Calculator(mockDataService);
        int result = calculator.calculateSum();

        assertEquals(6, result);
    }
}
OutputSuccess
Important Notes

Mocking avoids using real dependencies that might be slow or unreliable.

It helps focus tests on the code you want to check.

Always mock only external parts, not the code you want to test.

Summary

Mocking creates fake parts to isolate the code under test.

This makes tests faster and more reliable.

Use mocking to control what dependencies return during tests.