0
# Advanced Features and Integration
1
2
This section covers advanced Mockito features including session management, framework integration, custom plugins, and debugging utilities.
3
4
## Session Management
5
6
### MockitoSession Interface
7
8
Manage mock lifecycle with automatic cleanup and strictness control.
9
10
```java { .api }
11
public static MockitoSessionBuilder mockitoSession()
12
public static MockitoSession mockitoSession(Object... testClassInstances)
13
14
interface MockitoSession {
15
void setStrictness(Strictness strictness);
16
void finishMocking();
17
void finishMocking(Throwable failure);
18
}
19
20
interface MockitoSessionBuilder {
21
MockitoSessionBuilder name(String name);
22
MockitoSessionBuilder strictness(Strictness strictness);
23
MockitoSessionBuilder logger(MockitoSessionLogger logger);
24
MockitoSessionBuilder initMocks(Object... testClassInstances);
25
MockitoSession startMocking();
26
}
27
```
28
29
**Usage Examples:**
30
31
```java
32
class SessionManagedTest {
33
@Mock private UserService userService;
34
@Mock private EmailService emailService;
35
36
@Test
37
void testWithSession() {
38
MockitoSession session = mockitoSession()
39
.initMocks(this)
40
.name("UserRegistrationTest")
41
.strictness(Strictness.STRICT_STUBS)
42
.startMocking();
43
44
try {
45
// Test code with automatic mock management
46
given(userService.createUser(any())).willReturn(newUser);
47
48
// Test execution
49
registrationService.registerUser("john@example.com");
50
51
// Verification
52
then(userService).should().createUser(any());
53
54
} finally {
55
session.finishMocking(); // Validates unused stubs, etc.
56
}
57
}
58
59
@Test
60
void testWithTryWithResources() {
61
try (MockitoSession session = mockitoSession()
62
.initMocks(this)
63
.strictness(Strictness.LENIENT)
64
.startMocking()) {
65
66
// Test code - session automatically finished
67
}
68
}
69
}
70
```
71
72
### Custom Session Logger
73
74
Implement custom logging for session events.
75
76
```java { .api }
77
interface MockitoSessionLogger {
78
void log(String hint);
79
}
80
```
81
82
**Usage Example:**
83
84
```java
85
class CustomSessionLogger implements MockitoSessionLogger {
86
private final List<String> logs = new ArrayList<>();
87
88
@Override
89
public void log(String hint) {
90
logs.add("[MOCKITO] " + hint);
91
System.out.println(hint);
92
}
93
94
public List<String> getLogs() {
95
return Collections.unmodifiableList(logs);
96
}
97
}
98
99
@Test
100
void testWithCustomLogger() {
101
CustomSessionLogger logger = new CustomSessionLogger();
102
103
try (MockitoSession session = mockitoSession()
104
.logger(logger)
105
.startMocking()) {
106
107
// Test code
108
}
109
110
// Check logged hints
111
assertThat(logger.getLogs()).contains("Unused stubbings detected");
112
}
113
```
114
115
## Framework Integration
116
117
### MockitoFramework Interface
118
119
Access to framework-level functionality and plugins.
120
121
```java { .api }
122
public static MockitoFramework framework()
123
124
interface MockitoFramework {
125
MockitoPlugins getPlugins();
126
InvocationFactory getInvocationFactory();
127
MockitoSession mockitoSession();
128
void clearInlineMocks();
129
}
130
```
131
132
**Usage Examples:**
133
134
```java
135
@Test
136
void testFrameworkIntegration() {
137
MockitoFramework framework = framework();
138
139
// Access plugin system
140
MockMaker mockMaker = framework.getPlugins().getMockMaker();
141
System.out.println("Mock maker: " + mockMaker.getClass().getSimpleName());
142
143
// Create invocation factory for advanced scenarios
144
InvocationFactory factory = framework.getInvocationFactory();
145
146
// Clear inline mocks (useful for cleanup)
147
framework.clearInlineMocks();
148
}
149
```
150
151
### Plugin System
152
153
Access and configure Mockito plugins.
154
155
```java { .api }
156
interface MockitoPlugins {
157
MockMaker getMockMaker();
158
AnnotationEngine getAnnotationEngine();
159
StackTraceCleanerProvider getStackTraceCleanerProvider();
160
InstantiatorProvider getInstantiatorProvider();
161
}
162
```
163
164
**Usage Example:**
165
166
```java
167
@Test
168
void testPluginAccess() {
169
MockitoPlugins plugins = framework().getPlugins();
170
171
// Check which mock maker is being used
172
MockMaker mockMaker = plugins.getMockMaker();
173
if (mockMaker instanceof InlineMockMaker) {
174
System.out.println("Using inline mock maker - can mock final classes");
175
}
176
177
// Access annotation engine
178
AnnotationEngine engine = plugins.getAnnotationEngine();
179
System.out.println("Annotation engine: " + engine.getClass().getSimpleName());
180
}
181
```
182
183
## Debugging and Diagnostics
184
185
### Validation and Debugging
186
187
Tools for debugging mock usage and detecting issues.
188
189
```java { .api }
190
public static void validateMockitoUsage()
191
public static String mockitoInfo()
192
```
193
194
**Usage Examples:**
195
196
```java
197
@Test
198
void testWithValidation() {
199
List<String> mockList = mock(List.class);
200
201
// Setup and use mocks
202
when(mockList.get(0)).thenReturn("first");
203
mockList.get(0);
204
205
// Validate usage - throws exception if problems detected
206
validateMockitoUsage();
207
}
208
209
@Test
210
void testDebuggingInfo() {
211
// Get Mockito version and configuration info
212
String info = mockitoInfo();
213
System.out.println(info);
214
215
// Useful for troubleshooting environment issues
216
assertThat(info).contains("Mockito version");
217
}
218
```
219
220
### Mock State Inspection
221
222
Detailed inspection of mock objects and their state.
223
224
```java
225
@Test
226
void testMockInspection() {
227
List<String> mockList = mock(List.class);
228
229
// Use mock
230
when(mockList.get(0)).thenReturn("stubbed");
231
mockList.get(0);
232
mockList.size();
233
234
MockingDetails details = mockingDetails(mockList);
235
236
// Inspect invocations
237
Collection<Invocation> invocations = details.getInvocations();
238
System.out.println("Number of invocations: " + invocations.size());
239
240
for (Invocation invocation : invocations) {
241
System.out.println("Method: " + invocation.getMethod().getName());
242
System.out.println("Arguments: " + Arrays.toString(invocation.getArguments()));
243
System.out.println("Location: " + invocation.getLocation());
244
}
245
246
// Inspect stubbings
247
Collection<StubbingInfo> stubbings = details.getStubbings();
248
for (StubbingInfo stubbing : stubbings) {
249
System.out.println("Stubbing used: " + stubbing.wasUsed());
250
}
251
}
252
```
253
254
## Quality and Strictness
255
256
### Strictness Levels
257
258
Configure how strict Mockito should be about mock usage.
259
260
```java { .api }
261
enum Strictness {
262
LENIENT, // Most permissive
263
WARN, // Warn about potential issues
264
STRICT_STUBS // Fail on unused stubs
265
}
266
```
267
268
**Usage Examples:**
269
270
```java
271
class StrictnessTest {
272
273
@Test
274
void testLenientMode() {
275
// Lenient - unused stubs don't cause failures
276
List<String> mock = mock(List.class, withSettings().lenient());
277
278
when(mock.get(0)).thenReturn("never used"); // Won't cause test failure
279
when(mock.size()).thenReturn(5);
280
281
assertEquals(5, mock.size()); // Only this stub is used
282
// Test passes even though get(0) stub is unused
283
}
284
285
@Test
286
void testStrictMode() {
287
// Strict mode - all stubs must be used
288
List<String> mock = mock(List.class, withSettings().strictness(Strictness.STRICT_STUBS));
289
290
when(mock.size()).thenReturn(5);
291
292
assertEquals(5, mock.size());
293
// If we had unused stubs, test would fail
294
}
295
296
@Test
297
void testSessionStrictness() {
298
try (MockitoSession session = mockitoSession()
299
.strictness(Strictness.STRICT_STUBS)
300
.startMocking()) {
301
302
List<String> mock = mock(List.class);
303
when(mock.get(0)).thenReturn("must be used");
304
305
// Must use all stubs
306
mock.get(0);
307
} // Session validates on close
308
}
309
}
310
```
311
312
### MockitoHint for Quality
313
314
Get suggestions for improving test quality.
315
316
```java { .api }
317
class MockitoHint {
318
public static String get() { /* implementation */ }
319
}
320
```
321
322
## Custom Answers and Behaviors
323
324
### Advanced Answer Implementations
325
326
Create sophisticated mock behaviors.
327
328
```java
329
class AdvancedAnswers {
330
331
// Delegating answer that forwards to real object selectively
332
public static class SelectiveDelegateAnswer implements Answer<Object> {
333
private final Object delegate;
334
private final Set<String> methodsToDelegate;
335
336
public SelectiveDelegateAnswer(Object delegate, String... methods) {
337
this.delegate = delegate;
338
this.methodsToDelegate = Set.of(methods);
339
}
340
341
@Override
342
public Object answer(InvocationOnMock invocation) throws Throwable {
343
String methodName = invocation.getMethod().getName();
344
if (methodsToDelegate.contains(methodName)) {
345
return invocation.getMethod().invoke(delegate, invocation.getArguments());
346
}
347
return Answers.RETURNS_DEFAULTS.answer(invocation);
348
}
349
}
350
351
// Answer that tracks call counts
352
public static class CountingAnswer<T> implements Answer<T> {
353
private final AtomicInteger callCount = new AtomicInteger(0);
354
private final T returnValue;
355
356
public CountingAnswer(T returnValue) {
357
this.returnValue = returnValue;
358
}
359
360
@Override
361
public T answer(InvocationOnMock invocation) {
362
callCount.incrementAndGet();
363
return returnValue;
364
}
365
366
public int getCallCount() {
367
return callCount.get();
368
}
369
}
370
371
@Test
372
void testCustomAnswers() {
373
UserService mockService = mock(UserService.class);
374
375
// Use selective delegate answer
376
UserService realService = new UserService();
377
SelectiveDelegateAnswer answer = new SelectiveDelegateAnswer(realService, "validateUser");
378
379
when(mockService.validateUser(any())).thenAnswer(answer);
380
when(mockService.createUser(any())).thenReturn(mockUser);
381
382
// Use counting answer
383
CountingAnswer<Boolean> countingAnswer = new CountingAnswer<>(true);
384
when(mockService.isActive(any())).thenAnswer(countingAnswer);
385
386
// Test
387
mockService.isActive(user1);
388
mockService.isActive(user2);
389
390
assertEquals(2, countingAnswer.getCallCount());
391
}
392
}
393
```
394
395
## Integration Testing Utilities
396
397
### Verification Collector (JUnit 5)
398
399
Collect verification failures instead of failing immediately.
400
401
```java { .api }
402
interface VerificationCollector extends TestWatcher, AfterEachCallback {
403
// Collects verification failures for batch reporting
404
}
405
406
public static VerificationCollector collector()
407
```
408
409
**Usage Example:**
410
411
```java
412
@ExtendWith(MockitoExtension.class)
413
class CollectorTest {
414
415
@RegisterExtension
416
static VerificationCollector collector = MockitoJUnit.collector();
417
418
@Mock private UserService userService;
419
@Mock private EmailService emailService;
420
421
@Test
422
void testWithCollector() {
423
// Test code that might have multiple verification failures
424
userService.createUser("test");
425
426
// These verifications are collected, not immediately failing
427
collector.verify(() -> verify(userService).createUser("wrong-param"));
428
collector.verify(() -> verify(emailService).sendEmail(any()));
429
430
// All failures reported at end of test
431
}
432
}
433
```
434
435
## Performance and Optimization
436
437
### Mock Maker Selection
438
439
Choose appropriate mock maker for performance needs.
440
441
```java
442
class MockMakerTest {
443
444
@Test
445
void testInlineMockMaker() {
446
// Check if inline mock maker is available
447
if (framework().getPlugins().getMockMaker() instanceof InlineMockMaker) {
448
// Can mock final classes and methods
449
final class FinalClass {
450
final String getValue() { return "real"; }
451
}
452
453
FinalClass mock = mock(FinalClass.class);
454
when(mock.getValue()).thenReturn("mocked");
455
456
assertEquals("mocked", mock.getValue());
457
}
458
}
459
460
@Test
461
void testSubclassMockMaker() {
462
// Force subclass mock maker for testing
463
UserService mock = mock(UserService.class, withSettings()
464
.mockMaker("subclass"));
465
466
// Works with non-final classes only
467
when(mock.getUsers()).thenReturn(Collections.emptyList());
468
}
469
}
470
```
471
472
### Memory Management
473
474
Best practices for memory usage with mocks.
475
476
```java
477
class MemoryManagementTest {
478
479
@Test
480
void testMockCleanup() {
481
List<Object> mocks = new ArrayList<>();
482
483
// Create many mocks
484
for (int i = 0; i < 1000; i++) {
485
mocks.add(mock(UserService.class));
486
}
487
488
// Clear references
489
mocks.clear();
490
491
// Clear inline mocks if using inline mock maker
492
framework().clearInlineMocks();
493
494
// Force garbage collection for testing
495
System.gc();
496
}
497
}
498
```