0
0
JUnittesting~5 mins

Mock objects in JUnit

Choose your learning style9 modes available
Introduction

Mock objects help us test parts of a program by pretending to be other parts. This way, we can check if our code works without needing everything ready.

When the real object is not ready or hard to use during testing.
When the real object depends on slow or unreliable resources like databases or web services.
When you want to test how your code behaves with specific responses from other parts.
When you want to isolate the code you are testing from other parts to find bugs easily.
Syntax
JUnit
import static org.mockito.Mockito.*;

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

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

// Use mock in test
assertEquals(someValue, mockObject.someMethod());

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 example creates a mock list and tells it to return 5 when size() is called.
JUnit
MyList mockList = mock(MyList.class);
when(mockList.size()).thenReturn(5);
assertEquals(5, mockList.size());
This example mocks a service to return "Hello" when getData() is called.
JUnit
MyService mockService = mock(MyService.class);
when(mockService.getData()).thenReturn("Hello");
assertEquals("Hello", mockService.getData());
Sample Program

This test creates a mock UserRepository that returns "Alice" for ID 1. Then it checks if UserService returns the same name. This way, we test UserService without needing a real database.

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

class UserService {
    private UserRepository repo;
    public UserService(UserRepository repo) {
        this.repo = repo;
    }
    public String getUserName(int id) {
        return repo.findNameById(id);
    }
}

interface UserRepository {
    String findNameById(int id);
}

public class UserServiceTest {
    @Test
    void testGetUserName() {
        UserRepository mockRepo = mock(UserRepository.class);
        when(mockRepo.findNameById(1)).thenReturn("Alice");

        UserService service = new UserService(mockRepo);
        String name = service.getUserName(1);

        assertEquals("Alice", name);
    }
}
OutputSuccess
Important Notes

Mocks help isolate the code you want to test from other parts.

Always define what the mock should return to avoid unexpected results.

Mockito is a popular library for creating mocks in JUnit tests.

Summary

Mock objects pretend to be real objects for testing.

They help test code in isolation and control responses.

Use mock() and when(...).thenReturn(...) to create and control mocks.