0
0
JunitConceptBeginner · 3 min read

What is Mockito in JUnit: Simple Explanation and Example

In JUnit, Mockito is a popular library used to create mock objects for unit testing. It helps simulate the behavior of complex dependencies so you can test your code in isolation without needing real implementations.
⚙️

How It Works

Mockito works by creating fake versions of objects your code depends on, called mocks. Imagine you want to test a car's engine but don't want to use a real fuel pump. Mockito lets you create a pretend fuel pump that behaves as you tell it to, so you can focus on testing the engine alone.

When you run a test, Mockito intercepts calls to these mock objects and returns preset responses or tracks how they were used. This way, you can check if your code interacts correctly with its dependencies without needing the actual complex or slow components.

💻

Example

This example shows how to use Mockito in a JUnit test to mock a simple service dependency and verify behavior.

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

class UserService {
    private final UserRepository repo;
    public UserService(UserRepository repo) {
        this.repo = repo;
    }
    public String getUserName(int id) {
        User user = repo.findById(id);
        return user == null ? null : user.name();
    }
}

interface UserRepository {
    User findById(int id);
}

record User(int id, String name) {}

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

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

        assertEquals("Alice", name);
        verify(mockRepo).findById(1);
    }
}
Output
Test passed
🎯

When to Use

Use Mockito in JUnit tests when your code depends on other classes or services that are complex, slow, or have side effects like database access or network calls. Mocking lets you test your code quickly and reliably without needing those real parts.

For example, if you have a service that calls a payment gateway, you can mock the gateway to simulate success or failure responses. This helps you test how your service handles different scenarios without making real payments.

Key Points

  • Mockito creates mock objects to simulate dependencies.
  • It helps isolate the code under test for focused unit testing.
  • Mocks can return preset values and verify interactions.
  • Mockito integrates smoothly with JUnit 5 for easy testing.

Key Takeaways

Mockito lets you create fake objects to isolate and test code dependencies.
It helps write fast, reliable unit tests without real external systems.
Mockito can verify how your code interacts with its dependencies.
Use Mockito with JUnit to improve test clarity and maintainability.