Mockito for Java: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is Mockito and why is it needed?



Mockito is a powerful library for Java, designed for creating mock objects (stubs) in unit tests. It allows you to isolate the tested code from its dependencies, such as databases, external APIs, file systems, or other services. Instead of real objects, which can be slow, unstable, or require complex setup, you create their imitation with predefined behavior.



The main goal of Mockito is to make unit tests fast, predictable, and independent of the external environment. The library is widely used in the Java ecosystem (Spring, Java EE, Android) and is the de facto standard for mocking.



Key Features:

  • Creating mock objects — imitation of any class or interface.
  • Defining behavior — configuring return values, throwing exceptions.
  • Verifying calls — checking that methods were called with specific parameters and the required number of times.
  • Spy (partial mocking) — the ability to use a real object but override individual methods.
  • Argument Captor — extracting parameters passed to a mock method for further verification.


Installing Mockito



Since Mockito is a Java library, it is not installed via pip or npm. To add it to a project, Maven or Gradle build systems are used.



Maven (pom.xml)

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

<!-- For use with JUnit 5 --><dependency> <groupId>org.mockito</groupId> <artifactId>mockito-junit-jupiter</artifactId> <version>5.12.0</version> <scope>test</scope></dependency>


Gradle (build.gradle)

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


It is recommended to use the latest stable version, current at the time of writing the tests.



Quick Start: Code Example



Let's look at a simple example. Suppose we have a UserService class that depends on UserRepository. We want to test UserService without setting up a database.



// Repository class (dependency)public interface UserRepository {    User findById(Long id);    void save(User user);}

// Service class (tested)public class UserService { private final UserRepository userRepository;

public UserService(UserRepository userRepository) { this.userRepository = userRepository; }

public String getUserName(Long id) { User user = userRepository.findById(id); return user != null ? user.getName() : "Unknown"; }}

// Test using Mockitoimport org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;

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

@ExtendWith(MockitoExtension.class)public class UserServiceTest {

@Mock private UserRepository userRepository;

@Test public void testGetUserName() { // Create a mock object of UserRepository (can be done via @Mock annotation) // UserRepository mockRepo = mock(UserRepository.class);

// Configure behavior: when findById(1L) is called, return a user User mockUser = new User(1L, "Alice"); when(userRepository.findById(1L)).thenReturn(mockUser);

Recommendations