🧪 Introduction to Mockito: Unit Testing Made Easy in Java

🤔 What is Mockito?

Mockito is a powerful Java mocking framework used primarily for unit testing. It allows developers to simulate the behavior of real objects, making it easier to test code in isolation—without relying on actual dependencies like databases, web services, or other complex components.


🙋🏻 Why Use Mockito?

Mockito offers several key benefits:

  • Isolation: Focus on testing the class under test without being affected by the behavior of its collaborators.

  • Control: Easily simulate different scenarios such as success, failure, or exceptions.

  • Verification: Confirm that specific interactions (like method calls) occurred as expected.


📦 Adding Mockito to Your Project

👉 Maven

Add the following dependency to your pom.xml:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>5.12.0</version>
    <scope>test</scope>
</dependency>

👉 Gradle

testImplementation 'org.mockito:mockito-core:5.12.0'

💡 Example: Testing a Service with a Mocked Repository

Let’s test a simple RentingService class that depends on a RentingRequest.


🎯 Production Code

public class RentingService {
    public static final double BASE_PRICE_USD = 5.0;

    public double calculatePrice(RentingRequest rentingRequest) {
        Objects.requireNonNull(rentingRequest, "rentingRequest must not be null");
        long days = ChronoUnit.DAYS.between(rentingRequest.getDateFrom(), rentingRequest.getDateTo());
        if (days < 1) {
            throw new IllegalArgumentException("Rental duration must be at least 1 day");
        }
        return BASE_PRICE_USD * rentingRequest.getQuantity() * days;
    }
}
public class RentingRequest {
    private final String userId;
    private final LocalDate dateFrom;
    private final LocalDate dateTo;
    private final int quantity;
    private final boolean prepaid;
    private String bookId;

    public RentingRequest(String userId, LocalDate dateFrom, LocalDate dateTo, int quantity, boolean prepaid) {
        if (dateTo.isBefore(dateFrom)) {
            throw new IllegalArgumentException("dateTo cannot be before dateFrom");
        }
        if (quantity < 0) {
            throw new IllegalArgumentException("quantity must be non-negative");
        }
        this.userId = userId;
        this.dateFrom = dateFrom;
        this.dateTo = dateTo;
        this.quantity = quantity;
        this.prepaid = prepaid;
    }

    // Getters (if needed)
    public LocalDate getDateFrom() { return dateFrom; }
    public LocalDate getDateTo() { return dateTo; }
    public int getQuantity() { return quantity; }
}

🧪 Writing the Mockito Test

Let’s use JUnit 5 with Mockito annotations for a clean, expressive test.

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;

import java.time.LocalDate;
import java.time.Month;

import static org.junit.jupiter.api.Assertions.assertEquals;

@ExtendWith(MockitoExtension.class)
public class RentingServiceTest {

    @InjectMocks
    private RentingService rentingService;

    @Mock
    private MailSender mailSenderMock;

    @Spy
    private RentingDAO rentingDAOMock;

    @Test
    void should_CalculateCorrectPrice_When_ValidRequest() {
        RentingRequest rentingRequest = new RentingRequest(
                "1",
                LocalDate.of(2025, Month.JANUARY, 1),
                LocalDate.of(2025, Month.JANUARY, 5),
                2,
                false
        );

        double expected = RentingService.BASE_PRICE_USD * 2 * 4; // 2 items for 4 days
        double actual = rentingService.calculatePrice(rentingRequest);

        assertEquals(expected, actual, 0.001);
    }
}

🔍 Key Mockito Concepts

ConceptDescription
mock()Creates a fake object with default behavior.
when(...).thenReturn(...)Stubs specific method calls on mocks.
verify()Verifies that a method was called as expected.
@MockDeclares a mock object.
@InjectMocksInjects mock dependencies into the object under test.

🚀 Summary

Mockito is an essential tool for modern Java development. It helps you:

  • Write faster and more focused tests

  • Avoid slow and unreliable external dependencies

  • Gain confidence that your code behaves correctly in different scenarios

Start small: Mock a repository or service in your current project and see the immediate benefits of isolated, reliable unit testing.

🔗 Check out the full working demo on my GitHub

Happy testing! 🧪

1
Subscribe to my newsletter

Read articles from Buyandelger Tsendsuren directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Buyandelger Tsendsuren
Buyandelger Tsendsuren