0
# Verification and Interaction Testing
1
2
Verification in Mockito allows you to check that mock methods were called with expected arguments and frequencies. This is essential for testing interactions between objects.
3
4
## Basic Verification
5
6
### Simple Verification
7
8
Verify that a method was called:
9
10
```java { .api }
11
public static <T> T verify(T mock);
12
public static <T> T verify(T mock, VerificationMode mode);
13
```
14
15
**Usage Examples:**
16
17
```java
18
List<String> mock = mock(List.class);
19
20
// Use the mock
21
mock.add("item");
22
mock.clear();
23
24
// Verify interactions
25
verify(mock).add("item");
26
verify(mock).clear();
27
verify(mock).add(eq("item")); // Using argument matchers
28
```
29
30
## Verification Modes
31
32
Control how many times a method should be called:
33
34
```java { .api }
35
public static VerificationMode times(int wantedNumberOfInvocations);
36
public static VerificationMode never();
37
public static VerificationMode atLeastOnce();
38
public static VerificationMode atLeast(int minNumberOfInvocations);
39
public static VerificationMode atMost(int maxNumberOfInvocations);
40
public static VerificationMode only();
41
```
42
43
**Usage Examples:**
44
45
```java
46
List<String> mock = mock(List.class);
47
48
// Call method multiple times
49
mock.add("item1");
50
mock.add("item2");
51
mock.add("item3");
52
53
// Verify exact number of calls
54
verify(mock, times(3)).add(anyString());
55
verify(mock, times(1)).add("item1");
56
57
// Verify never called
58
verify(mock, never()).remove(anyString());
59
60
// Verify at least once
61
verify(mock, atLeastOnce()).add(anyString());
62
63
// Verify minimum number of calls
64
verify(mock, atLeast(2)).add(anyString());
65
66
// Verify maximum number of calls
67
verify(mock, atMost(5)).add(anyString());
68
69
// Verify this was the only interaction
70
verify(mock, only()).add(anyString());
71
```
72
73
### Times Alias
74
75
```java { .api }
76
public static VerificationMode calls(int wantedNumberOfInvocations);
77
```
78
79
This is an alias for `times()`:
80
81
```java
82
verify(mock, calls(3)).add(anyString());
83
// Equivalent to: verify(mock, times(3)).add(anyString());
84
```
85
86
## No Interactions Verification
87
88
Verify that no interactions occurred:
89
90
```java { .api }
91
public static void verifyNoMoreInteractions(Object... mocks);
92
public static void verifyZeroInteractions(Object... mocks);
93
```
94
95
**Usage Examples:**
96
97
```java
98
List<String> mock1 = mock(List.class);
99
List<String> mock2 = mock(List.class);
100
101
// Use mock1 but not mock2
102
mock1.add("item");
103
104
// Verify no interactions with mock2
105
verifyZeroInteractions(mock2);
106
107
// Verify mock1 had only the expected interaction
108
verify(mock1).add("item");
109
verifyNoMoreInteractions(mock1);
110
111
// Verify multiple mocks
112
verifyNoMoreInteractions(mock1, mock2);
113
```
114
115
## Ordered Verification
116
117
Verify that interactions happened in a specific order:
118
119
```java { .api }
120
public static InOrder inOrder(Object... mocks);
121
122
public interface InOrder {
123
<T> T verify(T mock);
124
<T> T verify(T mock, VerificationMode mode);
125
void verifyNoMoreInteractions();
126
}
127
```
128
129
**Usage Examples:**
130
131
```java
132
List<String> firstMock = mock(List.class);
133
List<String> secondMock = mock(List.class);
134
135
// Use mocks in specific order
136
firstMock.add("first");
137
secondMock.add("second");
138
firstMock.add("third");
139
140
// Verify order
141
InOrder inOrder = inOrder(firstMock, secondMock);
142
inOrder.verify(firstMock).add("first");
143
inOrder.verify(secondMock).add("second");
144
inOrder.verify(firstMock).add("third");
145
146
// Verify no more interactions in order
147
inOrder.verifyNoMoreInteractions();
148
```
149
150
## Timeout Verification
151
152
Verify interactions with timeout for asynchronous testing:
153
154
```java { .api }
155
public static VerificationWithTimeout timeout(long millis);
156
public static VerificationAfterDelay after(int millis);
157
```
158
159
**Usage Examples:**
160
161
```java
162
// Verify within timeout period
163
verify(mock, timeout(1000)).add("item");
164
165
// Verify with exact timeout
166
verify(mock, timeout(1000).times(1)).add("item");
167
168
// Verify after delay
169
verify(mock, after(100)).add("item");
170
171
// Combined with other modes
172
verify(mock, timeout(1000).atLeast(2)).add(anyString());
173
```
174
175
## Ignoring Stubs
176
177
Verify only interactions, not stubs:
178
179
```java { .api }
180
public static Object[] ignoreStubs(Object... mocks);
181
```
182
183
**Usage Examples:**
184
185
```java
186
List<String> mock = mock(List.class);
187
188
// Stub method
189
when(mock.get(0)).thenReturn("item");
190
191
// Use mock
192
mock.get(0); // This is stubbing interaction
193
mock.add("new item"); // This is real interaction
194
195
// Verify only real interactions, ignore stubs
196
verify(mock).add("new item");
197
verifyNoMoreInteractions(ignoreStubs(mock));
198
```
199
200
## Argument Verification
201
202
Verify method calls with specific argument values:
203
204
```java
205
List<String> mock = mock(List.class);
206
207
mock.add("exact string");
208
mock.add("another string");
209
210
// Verify exact arguments
211
verify(mock).add("exact string");
212
213
// Verify with argument matchers
214
verify(mock, times(2)).add(anyString());
215
verify(mock).add(startsWith("exact"));
216
verify(mock).add(contains("string"));
217
218
// Verify with custom matchers
219
verify(mock).add(argThat(s -> s.length() > 5));
220
```
221
222
## Verification Best Practices
223
224
### Verify Behavior, Not Implementation
225
226
```java
227
// Good - verify important interactions
228
verify(emailService).sendEmail(user.getEmail(), "Welcome!");
229
230
// Avoid - over-verification of internal details
231
verify(mock, times(1)).toString(); // Usually not important
232
```
233
234
### Use Appropriate Verification Modes
235
236
```java
237
// Good - verify expected behavior
238
verify(service, times(1)).processPayment(payment);
239
240
// Good - verify it never happens in error cases
241
verify(emailService, never()).sendEmail(anyString(), anyString());
242
243
// Avoid - over-specific verification
244
verify(service, times(1)).log(anyString()); // Logging is often implementation detail
245
```
246
247
### Combine with Argument Captors
248
249
```java
250
ArgumentCaptor<String> emailCaptor = ArgumentCaptor.forClass(String.class);
251
verify(emailService).sendEmail(emailCaptor.capture(), anyString());
252
assertEquals("user@example.com", emailCaptor.getValue());
253
```
254
255
### Order Verification Guidelines
256
257
```java
258
// Good - verify order when it matters
259
InOrder inOrder = inOrder(database, cache);
260
inOrder.verify(database).save(entity);
261
inOrder.verify(cache).invalidate(entity.getId());
262
263
// Avoid - unnecessary order verification
264
InOrder inOrder = inOrder(service1, service2);
265
inOrder.verify(service1).method1(); // If order doesn't matter for correctness
266
inOrder.verify(service2).method2();
267
```
268
269
## Common Verification Errors
270
271
### WantedButNotInvoked
272
273
```java
274
List<String> mock = mock(List.class);
275
verify(mock).add("item"); // Throws WantedButNotInvoked - method never called
276
```
277
278
### TooManyActualInvocations
279
280
```java
281
List<String> mock = mock(List.class);
282
mock.add("item");
283
mock.add("item");
284
verify(mock, times(1)).add("item"); // Throws TooManyActualInvocations
285
```
286
287
### ArgumentsAreDifferent
288
289
```java
290
List<String> mock = mock(List.class);
291
mock.add("actual");
292
verify(mock).add("expected"); // Throws ArgumentsAreDifferent
293
```
294
295
### Never but Invoked
296
297
```java
298
List<String> mock = mock(List.class);
299
mock.clear();
300
verify(mock, never()).clear(); // Throws NeverWantedButInvoked
301
```
302
303
## Advanced Verification Patterns
304
305
### Verification with Custom Matchers
306
307
```java
308
verify(service).process(argThat(request ->
309
request.getId() > 0 && request.getName() != null));
310
```
311
312
### Verification in Loops
313
314
```java
315
for (int i = 0; i < 3; i++) {
316
verify(mock).process(eq(i));
317
}
318
```
319
320
### Conditional Verification
321
322
```java
323
if (condition) {
324
verify(service).performAction();
325
} else {
326
verify(service, never()).performAction();
327
}
328
```