Java
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.
Exercise 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.
Show example solution
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);
}
}
Test yourself
-
What does a mock object do?
- Mimics the real object's behavior
- Connects to a real database
- Compiles the test
- Produces a test report
Show answer
Mimics the real object's behavior — A mock is a fake object that mimics the real one's behavior.
-
Complete the mock call
import static org.mockito.Mockito.*;
UserRepository repo = ____(UserRepository.class);
Show answer
import static org.mockito.Mockito.*;
UserRepository repo = mock(UserRepository.class);
-
Match the Mockito concepts
- mock
- Creates a fake object
- when
- Defines behavior
- verify
- Checks calls
- spy
- Wraps a real object
Next lesson: @Mock