0
# Mock Creation and Configuration
1
2
This section covers creating and configuring mock objects, spies, and advanced mock settings in Mockito.
3
4
## Basic Mock Creation
5
6
### Creating Mocks
7
8
Create mock instances of classes or interfaces.
9
10
```java { .api }
11
public static <T> T mock(Class<T> classToMock)
12
public static <T> T mock(Class<T> classToMock, String name)
13
public static <T> T mock(Class<T> classToMock, Answer defaultAnswer)
14
public static <T> T mock(Class<T> classToMock, MockSettings settings)
15
16
// Parameterless mock creation (since 4.10.0)
17
public static <T> T mock(T... reified)
18
public static <T> T mock(Answer defaultAnswer, T... reified)
19
public static <T> T mock(String name, T... reified)
20
public static <T> T mock(MockSettings settings, T... reified)
21
```
22
23
**Usage Examples:**
24
25
```java
26
// Basic mock creation
27
List<String> mockList = mock(List.class);
28
UserService mockUserService = mock(UserService.class);
29
30
// Named mock for better error messages
31
List<String> namedMock = mock(List.class, "userList");
32
33
// Mock with custom default answer
34
List<String> mockWithAnswer = mock(List.class, RETURNS_SMART_NULLS);
35
36
// Parameterless mock creation (automatic type detection)
37
List<String> autoMock = mock();
38
UserService autoUserService = mock();
39
40
// Parameterless with custom settings
41
List<String> customAutoMock = mock(RETURNS_SMART_NULLS);
42
List<String> namedAutoMock = mock("myList");
43
```
44
45
### Creating Spies
46
47
Create spies that wrap real objects, calling real methods unless stubbed.
48
49
```java { .api }
50
public static <T> T spy(T object)
51
public static <T> T spy(Class<T> classToSpy)
52
53
// Parameterless spy creation (since 4.10.0)
54
public static <T> T spy(T... reified)
55
```
56
57
**Usage Examples:**
58
59
```java
60
// Spy on existing object
61
List<String> realList = new ArrayList<>();
62
List<String> spyList = spy(realList);
63
64
// Spy on class (calls real constructor)
65
List<String> classSpy = spy(ArrayList.class);
66
67
// Parameterless spy creation (automatic type detection)
68
List<String> autoSpy = spy();
69
70
// Partial stubbing with spy
71
when(spyList.size()).thenReturn(100);
72
spyList.add("real method called");
73
```
74
75
## Mock Settings and Configuration
76
77
### MockSettings Interface
78
79
Advanced configuration for mock creation.
80
81
```java { .api }
82
public static MockSettings withSettings()
83
84
interface MockSettings {
85
MockSettings name(String name);
86
MockSettings defaultAnswer(Answer defaultAnswer);
87
MockSettings extraInterfaces(Class<?>... interfaces);
88
MockSettings serializable();
89
MockSettings serializable(SerializableMode mode);
90
MockSettings spiedInstance(Object spiedInstance);
91
MockSettings useConstructor(Object... constructorArgs);
92
MockSettings outerInstance(Object outerClassInstance);
93
MockSettings strictness(Strictness strictness);
94
MockSettings mockMaker(String mockMaker);
95
@Deprecated MockSettings lenient();
96
MockSettings invocationListeners(InvocationListener... listeners);
97
MockSettings verificationStartedListeners(VerificationStartedListener... listeners);
98
MockSettings stubbingLookupListeners(StubbingLookupListener... listeners);
99
MockSettings stubOnly();
100
MockSettings withoutAnnotations();
101
MockSettings verboseLogging();
102
MockSettings genericTypeToMock(Type genericTypeToMock);
103
<T> MockCreationSettings<T> build(Class<T> typeToMock);
104
<T> MockCreationSettings<T> buildStatic(Class<T> classToMock);
105
}
106
```
107
108
**Usage Examples:**
109
110
```java
111
// Mock with multiple interfaces
112
Foo mockFoo = mock(Foo.class, withSettings()
113
.extraInterfaces(Bar.class, Baz.class)
114
.name("fooMock"));
115
116
// Serializable mock
117
List<String> serializableMock = mock(List.class, withSettings()
118
.serializable());
119
120
// Mock with constructor arguments
121
UserService userService = mock(UserService.class, withSettings()
122
.useConstructor("database-url", 30));
123
124
// Lenient mock (bypasses strict stubbing)
125
List<String> lenientMock = mock(List.class, withSettings()
126
.lenient());
127
```
128
129
## Mock Introspection
130
131
### MockingDetails Interface
132
133
Inspect mock objects and their configuration.
134
135
```java { .api }
136
public static MockingDetails mockingDetails(Object toInspect)
137
138
interface MockingDetails {
139
boolean isMock();
140
boolean isSpy();
141
Object getMock();
142
Collection<Invocation> getInvocations();
143
Collection<Stubbing> getStubbings();
144
MockCreationSettings<?> getMockCreationSettings();
145
MockHandler getMockHandler();
146
String printInvocations();
147
}
148
```
149
150
**Usage Examples:**
151
152
```java
153
List<String> mockList = mock(List.class);
154
MockingDetails details = mockingDetails(mockList);
155
156
if (details.isMock()) {
157
System.out.println("Object is a mock");
158
}
159
160
if (details.isSpy()) {
161
System.out.println("Object is a spy");
162
}
163
164
// Get the mock object itself
165
Object mockObject = details.getMock();
166
167
// Get invocation history
168
Collection<Invocation> invocations = details.getInvocations();
169
170
// Get stubbing information
171
Collection<Stubbing> stubbings = details.getStubbings();
172
173
// Get mock creation settings
174
MockCreationSettings<?> settings = details.getMockCreationSettings();
175
Class<?> mockedType = settings.getTypeToMock();
176
String mockName = settings.getName();
177
178
// Get mock handler (for advanced framework integration)
179
MockHandler handler = details.getMockHandler();
180
181
// Print detailed mock information for debugging
182
System.out.println(details.printInvocations());
183
```
184
185
## Utility Methods
186
187
### Resetting Mocks
188
189
Reset mock objects to their initial state.
190
191
```java { .api }
192
public static void reset(Object... mocks)
193
```
194
195
**Usage Example:**
196
197
```java
198
List<String> mockList = mock(List.class);
199
when(mockList.size()).thenReturn(10);
200
201
// Use mock...
202
mockList.size(); // returns 10
203
204
// Reset removes all stubbing and interaction history
205
reset(mockList);
206
mockList.size(); // returns 0 (default)
207
```
208
209
### Clearing Invocations
210
211
Clear only invocation history while preserving stubbing.
212
213
```java { .api }
214
public static <T> void clearInvocations(T... mocks)
215
```
216
217
**Usage Example:**
218
219
```java
220
List<String> mockList = mock(List.class);
221
when(mockList.size()).thenReturn(10);
222
223
mockList.size(); // Invocation recorded
224
mockList.add("test"); // Another invocation
225
226
// Clear only invocations, keep stubbing
227
clearInvocations(mockList);
228
229
// Stubbing still works
230
assertEquals(10, mockList.size());
231
232
// But no previous invocations recorded for verification
233
verify(mockList, never()).add(anyString()); // Passes
234
```
235
236
### Clearing All Caches
237
238
Clear Mockito's internal caches and state.
239
240
```java { .api }
241
public static void clearAllCaches()
242
```
243
244
**Usage Example:**
245
246
```java
247
// Clear all Mockito state (rarely needed)
248
clearAllCaches();
249
```
250
251
### Framework Validation
252
253
Validate proper Mockito usage and detect potential issues.
254
255
```java { .api }
256
public static void validateMockitoUsage()
257
```
258
259
**Usage Example:**
260
261
```java
262
@Test
263
void testWithValidation() {
264
// Test code with mocks...
265
266
// Validate at end of test
267
validateMockitoUsage();
268
}
269
```
270
271
### Lenient Stubbing
272
273
Make individual stubbings bypass strict stubbing validation.
274
275
```java { .api }
276
public static LenientStubber lenient()
277
```
278
279
**Usage Example:**
280
281
```java
282
// Regular stubbing (subject to strict validation)
283
when(mock.someMethod()).thenReturn("value");
284
285
// Lenient stubbing (bypasses strict validation)
286
lenient().when(mock.someMethod()).thenReturn("value");
287
288
// Useful for stubbings that might not always be used
289
lenient().when(mock.optionalMethod()).thenReturn("fallback");
290
```
291
292
### Framework Integration
293
294
Access Mockito's framework for advanced integrations.
295
296
```java { .api }
297
public static MockitoFramework framework()
298
```
299
300
**Usage Example:**
301
302
```java
303
MockitoFramework framework = framework();
304
InvocationFactory invocationFactory = framework.getInvocationFactory();
305
306
// Access framework plugins
307
MockMaker mockMaker = framework.getPlugins().getMockMaker();
308
```
309
310
### Session Management
311
312
Manage mock sessions for better test isolation.
313
314
```java { .api }
315
public static MockitoSessionBuilder mockitoSession()
316
```
317
318
**Usage Example:**
319
320
```java
321
MockitoSession session = mockitoSession()
322
.initMocks(this)
323
.strictness(Strictness.STRICT_STUBS)
324
.logger(new CustomLogger())
325
.startMocking();
326
327
try {
328
// Test code with session-managed mocks
329
// ...
330
} finally {
331
session.finishMocking();
332
}
333
```
334
335
## Mock Types and Interfaces
336
337
### MockCreationSettings Interface
338
339
Contains immutable mock creation configuration.
340
341
```java { .api }
342
interface MockCreationSettings<T> {
343
Class<T> getTypeToMock();
344
Set<Class<?>> getExtraInterfaces();
345
String getName();
346
Object getSpiedInstance();
347
Answer<Object> getDefaultAnswer();
348
boolean isSerializable();
349
SerializableMode getSerializableMode();
350
List<InvocationListener> getInvocationListeners();
351
List<VerificationStartedListener> getVerificationStartedListeners();
352
boolean isStubOnly();
353
Strictness getStrictness();
354
boolean isLenient();
355
String getMockMaker();
356
Type getGenericTypeToMock();
357
Object getOuterClassInstance();
358
boolean isUsingConstructor();
359
Object[] getConstructorArgs();
360
}
361
```
362
363
### Enums and Constants
364
365
```java { .api }
366
enum SerializableMode {
367
NONE,
368
BASIC,
369
ACROSS_CLASSLOADERS
370
}
371
372
enum Strictness {
373
LENIENT,
374
WARN,
375
STRICT_STUBS
376
}
377
378
// Default Answer implementations
379
Answer<Object> RETURNS_DEFAULTS
380
Answer<Object> RETURNS_SMART_NULLS
381
Answer<Object> RETURNS_MOCKS
382
Answer<Object> RETURNS_DEEP_STUBS
383
Answer<Object> CALLS_REAL_METHODS
384
Answer<Object> RETURNS_SELF
385
```
386
387
### Framework Integration Interfaces
388
389
For advanced framework integrators.
390
391
```java { .api }
392
interface MockHandler {
393
Object handle(Invocation invocation) throws Throwable;
394
MockCreationSettings<?> getMockSettings();
395
InvocationContainer getInvocationContainer();
396
}
397
398
interface InvocationContainer {
399
// Marker interface for internal implementation
400
}
401
402
interface LenientStubber extends Stubber {
403
// Extends Stubber with lenient behavior
404
}
405
```
406
407
## Advanced Mock Configuration Examples
408
409
### Comprehensive MockSettings Example
410
411
```java
412
// Mock with all advanced settings
413
UserService mockUserService = mock(UserService.class, withSettings()
414
.name("userServiceMock")
415
.defaultAnswer(RETURNS_SMART_NULLS)
416
.extraInterfaces(Auditable.class, Cacheable.class)
417
.serializable(SerializableMode.ACROSS_CLASSLOADERS)
418
.strictness(Strictness.LENIENT)
419
.verboseLogging()
420
.invocationListeners(new CustomInvocationListener())
421
.verificationStartedListeners(new CustomVerificationListener())
422
.stubbingLookupListeners(new CustomStubbingListener()));
423
424
// Cast to extra interfaces
425
Auditable auditableMock = (Auditable) mockUserService;
426
Cacheable cacheableMock = (Cacheable) mockUserService;
427
```
428
429
### Constructor-based Mocking
430
431
```java
432
// Mock abstract class with constructor arguments
433
AbstractService mockService = mock(AbstractService.class, withSettings()
434
.useConstructor("database-url", 30, true)
435
.defaultAnswer(CALLS_REAL_METHODS));
436
437
// Mock inner class with outer instance
438
OuterClass outer = new OuterClass();
439
OuterClass.InnerClass mockInner = mock(OuterClass.InnerClass.class, withSettings()
440
.useConstructor()
441
.outerInstance(outer)
442
.defaultAnswer(CALLS_REAL_METHODS));
443
```
444
445
### Generic Type Preservation
446
447
```java
448
// Mock with generic type information
449
List<String> mockList = mock(List.class, withSettings()
450
.genericTypeToMock(new TypeReference<List<String>>() {}.getType()));
451
```
452
453
### Framework Integration Example
454
455
```java
456
// Advanced framework integration
457
MockSettings advancedSettings = withSettings()
458
.name("frameworkMock")
459
.stubOnly() // Memory optimization
460
.mockMaker("custom-mock-maker");
461
462
MockCreationSettings<UserService> settings = advancedSettings.build(UserService.class);
463
MockHandler handler = mockingDetails(mock).getMockHandler();
464
465
// Create invocation factory for programmatic invocations
466
InvocationFactory invocationFactory = framework().getInvocationFactory();
467
```