CodeBlanks Logo Icon CodeBlanks

Mock

Learn mock objects with Mockito.mock.

Mock

A mock is a fake object that mimics the behavior of a real one. With Mockito.mock() you create a mock of a class; tests are then isolated from dependencies (database, network).

UserRepository repo = mock(UserRepository.class);
when(repo.findById(1)).thenReturn(new User("Alex"));
User u = repo.findById(1);

Mocks make tests fast and predictable. You can try specific scenarios without connecting to a real database. This is the foundation of unit testing; you work isolated from side effects.

Mockito setup

Mockito is used together with JUnit 5. The mock() method is statically imported; this allows short call syntax.

import static org.mockito.Mockito.*;

UserRepository repo = mock(UserRepository.class);
MailService mail = mock(MailService.class);

Here repo and mail accept method calls like real objects; by default they return empty values. When you define behavior with when, they return specific values. This gives the test control over the dependencies.

Practice Mock a UserRepository

Define a User class (with a name field). Define a UserRepository interface with a User findById(int id) method. In a MockDemo class write a main method; build a real Map<Integer, User>, call put(1, new User("Alex")) and print the name of the user fetched with get(1). This simple structure simulates a mock.

Starter code

Main.java
import java.util.*;

// Define the User class (name field)

// Define the UserRepository interface (findById method)

// Write main in MockDemo and print the user's name

Sample solution

Main.java
import java.util.*;

class User {
    String name;
    User(String name) { this.name = name; }
}

interface UserRepository {
    User findById(int id);
}

class MockDemo {
    public static void main(String[] args) {
        Map<Integer, User> repo = new HashMap<>();
        repo.put(1, new User("Alex"));
        System.out.println(repo.get(1).name);
    }
}

Expected output

Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does a mock object do?

  • Mimics the real object's behavior Correct answer
  • Connects to a real database
  • Compiles the test
  • Produces a test report

Explanation: A mock is a fake object that mimics the real one's behavior.

2 Complete the mock call

Question
import static org.mockito.Mockito.*;

UserRepository repo = ____(UserRepository.class);
Answer
import static org.mockito.Mockito.*;

UserRepository repo = mock(UserRepository.class);

Explanation: mock() creates a fake object.

3 Match the Mockito concepts

Term Meaning
mock Creates a fake object
when Defines behavior
verify Checks calls
spy Wraps a real object

All lessons in Advanced