Mockito Cheatsheet¶
Installation¶
| Build Tool | Configuration |
|---|---|
| Maven | Add to pom.xml:<dependency><groupId>org.mockito</groupId><artifactId>mockito-core</artifactId><version>5.8.0</version><scope>test</scope></dependency> |
| Gradle | Add to build.gradle:testImplementation 'org.mockito:mockito-core:5.8.0' |
| Gradle (Kotlin) | Add to build.gradle.kts:testImplementation("org.mockito:mockito-core:5.8.0") |
| JUnit 5 Integration | Maven: mockito-junit-jupiter:5.8.0Gradle: testImplementation 'org.mockito:mockito-junit-jupiter:5.8.0' |
| Final Classes/Methods | Maven: mockito-inline:5.8.0Gradle: testImplementation 'org.mockito:mockito-inline:5.8.0' |
| Manual JAR | Download from Maven Central and add to classpath: Linux/macOS: export CLASSPATH=$CLASSPATH:/path/to/mockito-core-5.8.0.jarWindows: set CLASSPATH=%CLASSPATH%;C:\path\to\mockito-core-5.8.0.jar |
Basic Commands¶
| Command | Description |
|---|---|
mock(Class.class) |
Create a mock object of the specified class |
when(mock.method()).thenReturn(value) |
Stub a method to return a specific value |
verify(mock).method() |
Verify that a method was called once |
verify(mock, times(n)).method() |
Verify method was called exactly n times |
verify(mock, never()).method() |
Verify method was never called |
anyInt() |
Argument matcher for any integer value |
anyString() |
Argument matcher for any string value |
any(Class.class) |
Argument matcher for any object of specified class |
eq(value) |
Argument matcher for exact value match |
spy(object) |
Create a spy (partial mock) of a real object |
doThrow(exception).when(mock).method() |
Stub void method to throw exception |
doReturn(value).when(mock).method() |
Alternative stubbing syntax (safer for spies) |
verifyNoInteractions(mock) |
Verify no methods were called on mock |
verifyNoMoreInteractions(mock) |
Verify no other methods were called after verified ones |
reset(mock) |
Clear all stubbing and invocation history |
Annotation-Based Setup¶
| Annotation | Description |
|---|---|
@Mock |
Create a mock object automatically |
@InjectMocks |
Create instance and inject all @Mock dependencies |
@Spy |
Create a spy object automatically |
@Captor |
Create an ArgumentCaptor automatically |
@ExtendWith(MockitoExtension.class) |
JUnit 5: Enable Mockito annotations |
MockitoAnnotations.openMocks(this) |
Manually initialize mocks in @Before method |
@Mock(answer = RETURNS_DEEP_STUBS) |
Create mock with deep stubbing enabled |
@Mock(name = "customName") |
Create named mock for better debugging |
Stubbing Methods¶
| Command | Description |
|---|---|
when(mock.method()).thenReturn(val1, val2) |
Return different values on consecutive calls |
when(mock.method()).thenThrow(exception) |
Throw exception when method is called |
when(mock.method()).thenCallRealMethod() |
Call the real implementation |
when(mock.method()).thenAnswer(invocation -> {}) |
Custom answer with access to invocation details |
doNothing().when(mock).voidMethod() |
Explicitly stub void method to do nothing |
doAnswer(invocation -> {}).when(mock).method() |
Alternative answer syntax for void methods |
when(mock.method()).thenReturn(value).thenThrow(ex) |
Chain different behaviors |
mock(Class.class, RETURNS_SMART_NULLS) |
Return smart nulls instead of regular nulls |
mock(Class.class, RETURNS_DEEP_STUBS) |
Enable deep stubbing for chained calls |
mock(Class.class, withSettings().defaultAnswer(CALLS_REAL_METHODS)) |
Configure mock with custom settings |
Argument Matchers¶
| Matcher | Description |
|---|---|
anyInt(), anyLong(), anyDouble() |
Match any primitive numeric value |
anyString() |
Match any string value |
anyList(), anySet(), anyMap() |
Match any collection type |
any(Class.class) |
Match any object of specified type |
isNull(), isNotNull() |
Match null or non-null values |
eq(value) |
Match exact value (required when mixing matchers) |
contains("substring") |
Match string containing substring |
startsWith("prefix") |
Match string starting with prefix |
endsWith("suffix") |
Match string ending with suffix |
matches("regex") |
Match string against regex pattern |
argThat(matcher) |
Custom argument matcher with lambda |
intThat(matcher) |
Custom matcher for int primitives |
anyBoolean(), anyByte(), anyChar() |
Match any primitive value |
Verification Methods¶
| Command | Description |
|---|---|
verify(mock).method() |
Verify method called exactly once |
verify(mock, times(n)).method() |
Verify method called exactly n times |
verify(mock, atLeast(n)).method() |
Verify method called at least n times |
verify(mock, atMost(n)).method() |
Verify method called at most n times |
verify(mock, atLeastOnce()).method() |
Verify method called one or more times |
verify(mock, never()).method() |
Verify method never called |
verify(mock, only()).method() |
Verify this was the only method called |
verify(mock, timeout(millis)).method() |
Verify within timeout (async testing) |
verify(mock, after(millis)).method() |
Verify after waiting specified time |
verify(mock, timeout(millis).times(n)).method() |
Combine timeout with invocation count |
verify(mock, description("custom message")).method() |
Add custom failure message |
Argument Captors¶
| Command | Description |
|---|---|
ArgumentCaptor.forClass(Class.class) |
Create argument captor for specified type |
captor.capture() |
Capture argument during verification |
captor.getValue() |
Get the captured argument value |
captor.getAllValues() |
Get list of all captured values (multiple calls) |
@Captor ArgumentCaptor<Type> captor |
Create captor using annotation |
// Example: Capturing and asserting arguments
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
verify(userService).save(userCaptor.capture());
User capturedUser = userCaptor.getValue();
assertEquals("John", capturedUser.getName());
Advanced Features¶
| Feature | Description |
|---|---|
InOrder inOrder = inOrder(mock1, mock2) |
Create ordered verifier for multiple mocks |
inOrder.verify(mock).method() |
Verify method called in specific order |
mockStatic(StaticClass.class) |
Mock static methods (requires mockito-inline) |
mockConstruction(Class.class) |
Mock constructor calls (requires mockito-inline) |
mock(FinalClass.class) |
Mock final classes (requires mockito-inline) |
Mockito.lenient().when(mock.method()) |
Create lenient stubbing (won't fail on unused stubs) |
clearInvocations(mock) |
Clear invocation history but keep stubs |
validateMockitoUsage() |
Detect incorrect Mockito usage in tests |
Mockito.framework().clearInlineMocks() |
Clear all inline mocks (static/constructor) |
BDD Style (Behavior-Driven Development)¶
| Command | Description |
|---|---|
given(mock.method()).willReturn(value) |
BDD-style stubbing (alias for when) |
given(mock.method()).willThrow(exception) |
BDD-style exception stubbing |
willReturn(value).given(mock).method() |
Alternative BDD syntax for void methods |
willThrow(exception).given(mock).method() |
BDD-style exception for void methods |
then(mock).should().method() |
BDD-style verification (alias for verify) |
then(mock).should(times(n)).method() |
BDD-style verification with count |
then(mock).shouldHaveNoInteractions() |
BDD-style no interactions check |
then(mock).shouldHaveNoMoreInteractions() |
BDD-style no more interactions check |
Configuration¶
Test Class Setup with JUnit 5¶
import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.junit.jupiter.MockitoExtension;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@Mock
private EmailService emailService;
@InjectMocks
private UserService userService;
@Test
void testUserCreation() {
User user = new User("John");
when(userRepository.save(any(User.class))).thenReturn(user);
User result = userService.createUser("John");
verify(userRepository).save(any(User.class));
verify(emailService).sendWelcomeEmail(user);
assertEquals("John", result.getName());
}
}
Test Class Setup with JUnit 4¶
import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.*;
public class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
public void testUserCreation() {
// Test implementation
}
}
Custom Mock Settings¶
// Create mock with custom settings
UserService mock = mock(UserService.class, withSettings()
.name("customMockName")
.defaultAnswer(RETURNS_SMART_NULLS)
.serializable()
.verboseLogging());
// Create mock with invocation listeners
UserService mock = mock(UserService.class, withSettings()
.invocationListeners(invocation -> {
System.out.println("Method called: " + invocation.getMethod());
}));
Mockito Configuration File¶
Create mockito-extensions/org.mockito.plugins.MockMaker in test resources:
This enables mocking of final classes and methods without explicit dependency.
Common Use Cases¶
Use Case 1: Testing Service Layer with Repository¶
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
void shouldFindUserById() {
// Given
User expectedUser = new User(1L, "John");
when(userRepository.findById(1L)).thenReturn(Optional.of(expectedUser));
// When
User result = userService.getUserById(1L);
// Then
assertEquals("John", result.getName());
verify(userRepository).findById(1L);
}
}
Use Case 2: Testing Exception Handling¶
@Test
void shouldHandleUserNotFoundException() {
// Given
when(userRepository.findById(999L))
.thenThrow(new UserNotFoundException("User not found"));
// When & Then
assertThrows(UserNotFoundException.class, () -> {
userService.getUserById(999L);
});
verify(userRepository).findById(999L);
}
Use Case 3: Verifying Method Call Order¶
@Test
void shouldProcessUserInCorrectOrder() {
// Given
User user = new User("John");
// When
userService.registerUser(user);
// Then
InOrder inOrder = inOrder(userRepository, emailService, auditService);
inOrder.verify(userRepository).save(user);
inOrder.verify(emailService).sendWelcomeEmail(user);
inOrder.verify(auditService).logRegistration(user);
}
Use Case 4: Capturing and Asserting Arguments¶
@Test
void shouldSaveUserWithCorrectData() {
// Given
ArgumentCaptor<User> userCaptor = ArgumentCaptor.forClass(User.class);
// When
userService.createUser("John", "john@example.com");
// Then
verify(userRepository).save(userCaptor.capture());
User capturedUser = userCaptor.getValue();
assertEquals("John", capturedUser.getName());
assertEquals("john@example.com", capturedUser.getEmail());
assertNotNull(capturedUser.getCreatedDate());
}
Use Case 5: Testing Asynchronous Code¶
@Test
void shouldProcessAsyncOperation() {
// Given
when(asyncService.processData(anyString()))
.thenReturn(CompletableFuture.completedFuture("result"));
// When
userService.processUserAsync("user123");
// Then - verify within timeout for async operations
verify(asyncService, timeout(1000)).processData("user123");
verify(notificationService, timeout(1000)).sendNotification(any());
}
Use Case 6: Mocking Static Methods¶
@Test
void shouldMockStaticUtilityMethod() {
try (MockedStatic<DateUtils> dateUtils = mockStatic(DateUtils.class)) {
// Given
LocalDate fixedDate = LocalDate.of(2024, 1, 1);
dateUtils.when(DateUtils::getCurrentDate).thenReturn(fixedDate);
// When
User user = userService.createUser("John");
// Then
assertEquals(fixedDate, user.getRegistrationDate());
dateUtils.verify(DateUtils::getCurrentDate);
}
}
Use Case 7: Using Spies for Partial Mocking¶
@Test
void shouldUseSpyForPartialMocking() {
// Given
UserService realService = new UserService(userRepository);
UserService spyService = spy(realService);
// Stub only specific method
doReturn(true).when(spyService).isValidEmail(anyString());
// When
User user = spyService.createUser("John", "invalid-email");
// Then - real methods called except stubbed ones
verify(spyService).isValidEmail("invalid-email");
verify(userRepository).save(any(User.class));
}
Best Practices¶
-
Use
@Mockand@InjectMocksannotations instead of manual mock creation for cleaner test code and automatic dependency injection -
Prefer
when().thenReturn()overdoReturn().when()for regular mocking; usedoReturn()only for spies or when stubbing methods that throw exceptions -
Don't mock types you don't own (e.g., third-party libraries) - instead, create wrapper interfaces and mock those to maintain control over your test boundaries
-
Verify behavior, not implementation details - focus on testing what the code does, not how it does it; avoid over-verification that makes tests brittle
-
Use argument captors sparingly - only when you need to assert complex argument values; prefer argument matchers for simple verification
-
Keep one logical assertion per test - tests should verify a single behavior to make failures easy to diagnose and maintain
-
Clean up static mocks properly - always use try-with-resources when mocking static methods to prevent state leakage between tests
-
Use
lenient()for optional stubs - when stubbing methods that might not be called in all test scenarios, mark them as lenient to avoid unnecessary strict stubbing errors -
Avoid mocking value objects - mock only objects with behavior (services, repositories); use real instances for DTOs, entities, and value objects
-
Name your mocks descriptively - when debugging complex tests, use
mock(Class.class, "descriptiveName")to make error messages clearer
Troubleshooting¶
| Issue | Solution |
|---|---|
| UnnecessaryStubbingException: Stubbed method not called in test | Remove unused stubs or mark as lenient: lenient().when(mock.method()).thenReturn(value) |
| Cannot mock final class/method | Add mockito-inline dependency or create mockito-extensions/org.mockito.plugins.MockMaker with content mock-maker-inline |
| NullPointerException when calling mocked method | Ensure mock is properly initialized with MockitoAnnotations.openMocks(this) or @ExtendWith(MockitoExtension.class) |
| ArgumentMatchers can't be used outside stubbing/verification | Don't store matcher results in variables; use them directly in when() or verify() calls |
| WrongTypeOfReturnValue: Cannot return X for method returning Y | Check return type matches method signature; use correct stubbing method (e.g., thenReturn() vs thenThrow()) |
| Mixing argument matchers and raw values | When using matchers like anyString(), all arguments must use matchers; wrap raw values with eq(): verify(mock).method(eq("raw"), anyString()) |
| TooManyActualInvocations: Method called more times than expected | Verify actual invocation count with verify(mock, times(n)) or check for unintended repeated calls in production code |
| MockitoException: Cannot instantiate @InjectMocks | Ensure class has a no-arg constructor or constructor with all @Mock dependencies; check for final fields without initialization |
| Spy stubbing causes real method invocation | Use doReturn().when(spy) instead of when(spy).thenReturn() to avoid calling real method during stubbing |
| Static mock not working | Ensure mockito-inline dependency is included and use try-with-resources: try (MockedStatic<Class> mock = mockStatic(Class.class)) { } |
| NoSuchMethodError or ClassNotFoundException | Check Mockito version compatibility with your JUnit version; ensure all dependencies are consistent |
| InOrder verification fails unexpectedly | Remember that InOrder only verifies specified interactions; other method calls can occur between verified calls |
Quick Reference Import Statements:
import static org.mockito.Mockito.*;
import static org.mockito.BDDMockito.*;
import static org.mockito.ArgumentMatchers.*;
import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.Captor;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.junit.jupiter.MockitoExtension;
import org.junit.jupiter.api.extension.ExtendWith;