0
# Mockito
1
2
Mockito is a comprehensive Java mocking framework that enables developers to create test doubles for unit testing. It provides a clean and simple API for creating mocks, stubs, and spies, allowing developers to verify interactions, stub method calls, and write readable tests with clear verification error messages.
3
4
## Package Information
5
6
- **Package Name**: org.mockito:mockito-all
7
- **Package Type**: Maven
8
- **Language**: Java
9
- **Version**: 1.10.19
10
- **Installation**: Add to Maven dependencies:
11
```xml
12
<dependency>
13
<groupId>org.mockito</groupId>
14
<artifactId>mockito-all</artifactId>
15
<version>1.10.19</version>
16
<scope>test</scope>
17
</dependency>
18
```
19
- **Gradle**: `testCompile 'org.mockito:mockito-all:1.10.19'`
20
21
**Note**: For newer projects, consider using `org.mockito:mockito-core` instead of `mockito-all`. The `mockito-all` artifact includes all dependencies bundled together, while `mockito-core` provides better dependency management flexibility.
22
23
## Core Imports
24
25
```java
26
import static org.mockito.Mockito.*;
27
import static org.mockito.Matchers.*;
28
```
29
30
For BDD-style testing:
31
```java
32
import static org.mockito.BDDMockito.*;
33
```
34
35
## Basic Usage
36
37
```java
38
import static org.mockito.Mockito.*;
39
import static org.mockito.Matchers.*;
40
import java.util.List;
41
42
public class MockitoExampleTest {
43
44
@Test
45
public void testMockCreationAndVerification() {
46
// Create mock
47
List<String> mockedList = mock(List.class);
48
49
// Use mock object
50
mockedList.add("one");
51
mockedList.clear();
52
53
// Verification
54
verify(mockedList).add("one");
55
verify(mockedList).clear();
56
}
57
58
@Test
59
public void testStubbing() {
60
// Create mock
61
List<String> mockedList = mock(List.class);
62
63
// Stubbing
64
when(mockedList.get(0)).thenReturn("first");
65
when(mockedList.get(1)).thenThrow(new RuntimeException());
66
67
// Usage
68
System.out.println(mockedList.get(0)); // prints "first"
69
70
// Verification
71
verify(mockedList).get(0);
72
}
73
}
74
```
75
76
## Architecture
77
78
Mockito is built around several key components:
79
80
- **Mock Creation**: Create mock objects of classes and interfaces using `mock()` and `spy()`
81
- **Stubbing API**: Define behavior for mock methods using `when().thenReturn()` family
82
- **Verification System**: Verify mock interactions with `verify()` and various verification modes
83
- **Argument Matching**: Flexible argument matching with `any()`, `eq()`, and custom matchers
84
- **Annotation Support**: Shorthand creation with `@Mock`, `@Spy`, `@InjectMocks`, and `@Captor`
85
- **BDD Integration**: Behavior-driven development style with `given().willReturn()` syntax
86
87
## Capabilities
88
89
### Mock Creation and Spying
90
91
Core functionality for creating mock objects and spies. Supports mocking classes, interfaces, and creating partial mocks through spying on real objects.
92
93
```java { .api }
94
public static <T> T mock(Class<T> classToMock);
95
public static <T> T mock(Class<T> classToMock, String name);
96
public static <T> T mock(Class<T> classToMock, Answer defaultAnswer);
97
public static <T> T mock(Class<T> classToMock, MockSettings mockSettings);
98
public static <T> T spy(T object);
99
public static <T> T spy(Class<T> classToSpy);
100
public static MockSettings withSettings();
101
public static MockingDetails mockingDetails(Object toInspect);
102
```
103
104
[Mock Creation and Spying](./mock-creation.md)
105
106
### Method Stubbing
107
108
Define behavior for mock method calls including return values, exceptions, and custom answers. Supports both traditional and BDD-style stubbing syntax.
109
110
```java { .api }
111
public static <T> OngoingStubbing<T> when(T methodCall);
112
public static Stubber doReturn(Object toBeReturned);
113
public static Stubber doThrow(Throwable toBeThrown);
114
public static Stubber doAnswer(Answer answer);
115
public static Stubber doNothing();
116
public static Stubber doCallRealMethod();
117
118
// AdditionalAnswers utility methods
119
public static <T> Answer<T> returnsFirstArg();
120
public static <T> Answer<T> returnsSecondArg();
121
public static <T> Answer<T> returnsLastArg();
122
public static <T> Answer<T> returnsArgAt(int position);
123
public static <T> Answer<T> delegatesTo(Object delegate);
124
public static <T> Answer<T> returnsElementsOf(Collection<?> elements);
125
```
126
127
[Method Stubbing](./stubbing.md)
128
129
### Verification and Interaction Testing
130
131
Verify that mock methods were called with expected arguments and frequencies. Includes ordered verification and comprehensive verification modes.
132
133
```java { .api }
134
public static <T> T verify(T mock);
135
public static <T> T verify(T mock, VerificationMode mode);
136
public static VerificationMode times(int wantedNumberOfInvocations);
137
public static VerificationMode never();
138
public static VerificationMode atLeastOnce();
139
public static VerificationMode atLeast(int minNumberOfInvocations);
140
public static VerificationMode atMost(int maxNumberOfInvocations);
141
public static VerificationMode only();
142
public static VerificationMode calls(int wantedNumberOfInvocations);
143
public static VerificationWithTimeout timeout(long millis);
144
public static VerificationAfterDelay after(int millis);
145
public static void verifyNoMoreInteractions(Object... mocks);
146
public static void verifyZeroInteractions(Object... mocks);
147
public static InOrder inOrder(Object... mocks);
148
public static Object[] ignoreStubs(Object... mocks);
149
```
150
151
[Verification](./verification.md)
152
153
### Argument Matching
154
155
Flexible argument matching for stubbing and verification, including built-in matchers for common types and custom matcher support.
156
157
```java { .api }
158
// Basic matchers
159
public static <T> T any();
160
public static <T> T any(Class<T> clazz);
161
public static <T> T eq(T value);
162
public static <T> T same(T value);
163
public static <T> T isNull();
164
public static <T> T isNotNull();
165
166
// Primitive type matchers
167
public static String anyString();
168
public static int anyInt();
169
public static long anyLong();
170
public static double anyDouble();
171
public static boolean anyBoolean();
172
173
// Collection matchers
174
public static List anyList();
175
public static <T> List<T> anyListOf(Class<T> clazz);
176
public static Set anySet();
177
public static Map anyMap();
178
public static Collection anyCollection();
179
180
// String matchers
181
public static String contains(String substring);
182
public static String matches(String regex);
183
public static String startsWith(String prefix);
184
public static String endsWith(String suffix);
185
186
// Custom matchers
187
public static <T> T argThat(Matcher<T> matcher);
188
189
// AdditionalMatchers comparison and logical
190
public static <T> T not(T value);
191
public static <T> T or(T left, T right);
192
public static <T> T and(T left, T right);
193
public static <T extends Comparable<T>> T geq(T value);
194
public static <T extends Comparable<T>> T leq(T value);
195
public static <T extends Comparable<T>> T gt(T value);
196
public static <T extends Comparable<T>> T lt(T value);
197
```
198
199
[Argument Matching](./matchers.md)
200
201
### Annotation-Based Testing
202
203
Streamlined test setup using annotations for mock creation, spy creation, and dependency injection with automatic initialization.
204
205
```java { .api }
206
@Target(FIELD) @Retention(RUNTIME)
207
public @interface Mock {
208
Answers answer() default Answers.RETURNS_DEFAULTS;
209
String name() default "";
210
Class<?>[] extraInterfaces() default {};
211
boolean serializable() default false;
212
}
213
214
@Target(FIELD) @Retention(RUNTIME)
215
public @interface Spy { }
216
217
@Target(FIELD) @Retention(RUNTIME)
218
public @interface InjectMocks { }
219
220
@Target(FIELD) @Retention(RUNTIME)
221
public @interface Captor { }
222
```
223
224
[Annotations](./annotations.md)
225
226
### Argument Capturing
227
228
Capture method arguments during verification for detailed assertions, supporting both single values and multiple invocations.
229
230
```java { .api }
231
public class ArgumentCaptor<T> {
232
public static <T> ArgumentCaptor<T> forClass(Class<T> clazz);
233
public T capture();
234
public T getValue();
235
public List<T> getAllValues();
236
}
237
```
238
239
[Argument Capturing](./argument-capturing.md)
240
241
### BDD-Style Testing
242
243
Behavior-driven development syntax using given/when/then structure for more readable test specifications.
244
245
```java { .api }
246
public static <T> BDDMyOngoingStubbing<T> given(T methodCall);
247
public static <T> BDDStubber willReturn(T value);
248
public static BDDStubber willThrow(Throwable... throwables);
249
public static <T> Then<T> then(T mock);
250
```
251
252
[BDD Style Testing](./bdd-testing.md)
253
254
### JUnit Integration
255
256
Seamless integration with JUnit testing framework through runners and rules for automatic mock initialization and enhanced debugging.
257
258
```java { .api }
259
public class MockitoJUnitRunner extends Runner;
260
public class VerboseMockitoJUnitRunner extends MockitoJUnitRunner;
261
262
public interface MockitoRule extends TestRule;
263
public class MockitoJUnit {
264
public static MockitoRule rule();
265
}
266
```
267
268
[JUnit Integration](./junit-integration.md)
269
270
### Mock Utilities
271
272
Framework utilities for mock reset, stub management, and framework validation.
273
274
```java { .api }
275
public static <T> void reset(T... mocks);
276
public static Object[] ignoreStubs(Object... mocks);
277
public static void validateMockitoUsage();
278
```
279
280
## Exception Handling
281
282
Mockito provides comprehensive exception types for different error scenarios:
283
284
- **MockitoException**: Base exception for framework errors
285
- **InvalidUseOfMatchersException**: Incorrect argument matcher usage
286
- **MissingMethodInvocationException**: Missing method call in stubbing
287
- **WantedButNotInvoked**: Expected method not called during verification
288
- **TooManyActualInvocations**: More method calls than expected
289
290
## Version Features
291
292
### Version 1.8.0+
293
- Argument capturing with ArgumentCaptor
294
- Real partial mocks
295
- Mock resetting capabilities
296
- Framework usage validation
297
298
### Version 1.9.0+
299
- Automatic @Spy/@InjectMocks instantiation
300
- One-liner stubs
301
- Verification ignoring stubs
302
303
### Version 1.10.0+
304
- BDD style verification with then()
305
- Abstract class mocking and spying (1.10.12+)
306
307
## Types
308
309
```java { .api }
310
public interface Answer<T> {
311
T answer(InvocationOnMock invocation) throws Throwable;
312
}
313
314
public interface OngoingStubbing<T> {
315
OngoingStubbing<T> thenReturn(T value);
316
OngoingStubbing<T> thenReturn(T value, T... values);
317
OngoingStubbing<T> thenThrow(Throwable... throwables);
318
OngoingStubbing<T> thenAnswer(Answer<?> answer);
319
OngoingStubbing<T> thenCallRealMethod();
320
T getMock();
321
}
322
323
public interface Stubber {
324
<T> T when(T mock);
325
Stubber doReturn(Object toBeReturned);
326
Stubber doThrow(Throwable... toBeThrown);
327
Stubber doAnswer(Answer answer);
328
Stubber doNothing();
329
Stubber doCallRealMethod();
330
}
331
332
public interface VerificationMode { }
333
334
public interface VerificationWithTimeout extends VerificationMode {
335
VerificationMode atMost(int maxNumberOfInvocations);
336
VerificationMode never();
337
}
338
339
public interface VerificationAfterDelay extends VerificationMode { }
340
341
public interface InOrder {
342
<T> T verify(T mock);
343
<T> T verify(T mock, VerificationMode mode);
344
void verifyNoMoreInteractions();
345
}
346
347
public interface MockSettings {
348
MockSettings name(String name);
349
MockSettings defaultAnswer(Answer defaultAnswer);
350
MockSettings extraInterfaces(Class<?>... interfaces);
351
MockSettings serializable();
352
MockSettings serializable(SerializableMode mode);
353
MockSettings verboseLogging();
354
MockSettings spiedInstance(Object instance);
355
MockSettings invocationListeners(InvocationListener... listeners);
356
MockSettings stubOnly();
357
MockSettings useConstructor();
358
MockSettings outerInstance(Object outerClassInstance);
359
}
360
361
public enum Answers {
362
RETURNS_DEFAULTS,
363
RETURNS_SMART_NULLS,
364
RETURNS_MOCKS,
365
RETURNS_DEEP_STUBS,
366
CALLS_REAL_METHODS
367
}
368
369
public interface MockingDetails {
370
boolean isMock();
371
boolean isSpy();
372
Collection<Invocation> getInvocations();
373
}
374
```