0
# Verification and Assertions
1
2
This section covers verifying method invocations on mock objects, including basic verification, verification modes, ordered verification, and timeout verification.
3
4
## Basic Verification
5
6
### Standard Verification
7
8
Verify that methods were called on mock objects.
9
10
```java { .api }
11
public static <T> T verify(T mock)
12
public static <T> T verify(T mock, VerificationMode mode)
13
public static void verifyNoMoreInteractions(Object... mocks)
14
public static void verifyNoInteractions(Object... mocks)
15
```
16
17
**Usage Examples:**
18
19
```java
20
List<String> mockList = mock(List.class);
21
22
// Use mock
23
mockList.add("item");
24
mockList.clear();
25
26
// Verify method calls
27
verify(mockList).add("item");
28
verify(mockList).clear();
29
30
// Verify no additional interactions
31
verifyNoMoreInteractions(mockList);
32
33
// For completely unused mocks
34
List<String> unusedMock = mock(List.class);
35
verifyNoInteractions(unusedMock);
36
```
37
38
## Verification Modes
39
40
### Times Verification
41
42
Verify specific number of invocations.
43
44
```java { .api }
45
public static VerificationMode times(int wantedNumberOfInvocations)
46
public static VerificationMode never()
47
public static VerificationMode atLeastOnce()
48
public static VerificationMode atLeast(int minNumberOfInvocations)
49
public static VerificationMode atMost(int maxNumberOfInvocations)
50
public static VerificationMode only()
51
```
52
53
**Usage Examples:**
54
55
```java
56
List<String> mockList = mock(List.class);
57
58
// Use mock multiple times
59
mockList.add("one");
60
mockList.add("two");
61
mockList.size();
62
63
// Verify exact number of calls
64
verify(mockList, times(2)).add(anyString());
65
verify(mockList, times(1)).size();
66
67
// Verify method never called
68
verify(mockList, never()).clear();
69
70
// Range verifications
71
verify(mockList, atLeast(1)).add(anyString());
72
verify(mockList, atMost(3)).add(anyString());
73
verify(mockList, atLeastOnce()).size();
74
75
// Only this method was called (no other interactions)
76
List<String> singleUseMock = mock(List.class);
77
singleUseMock.isEmpty();
78
verify(singleUseMock, only()).isEmpty();
79
```
80
81
### Timeout Verification
82
83
Verify method calls within a time limit, useful for asynchronous testing.
84
85
```java { .api }
86
public static VerificationWithTimeout timeout(long millis)
87
public static VerificationAfterDelay after(long millis)
88
89
interface VerificationWithTimeout extends VerificationMode {
90
VerificationWithTimeout times(int wantedNumberOfInvocations);
91
VerificationWithTimeout atLeast(int minNumberOfInvocations);
92
VerificationWithTimeout atMost(int maxNumberOfInvocations);
93
VerificationWithTimeout only();
94
VerificationWithTimeout never();
95
}
96
```
97
98
**Usage Examples:**
99
100
```java
101
// Async service that calls callback
102
AsyncService mockService = mock(AsyncService.class);
103
Callback mockCallback = mock(Callback.class);
104
105
// Start async operation
106
mockService.processAsync(data, mockCallback);
107
108
// Verify callback is called within 1 second
109
verify(mockCallback, timeout(1000)).onComplete(any());
110
111
// Verify multiple calls within timeout
112
verify(mockCallback, timeout(2000).times(3)).onProgress(anyInt());
113
114
// Verify after delay (doesn't wait, just delays verification)
115
verify(mockCallback, after(100)).onComplete(any());
116
```
117
118
## Ordered Verification
119
120
### InOrder Verification
121
122
Verify that interactions happened in specific order.
123
124
```java { .api }
125
public static InOrder inOrder(Object... mocks)
126
127
interface InOrder {
128
<T> T verify(T mock);
129
<T> T verify(T mock, VerificationMode mode);
130
void verifyNoMoreInteractions();
131
}
132
```
133
134
**Usage Examples:**
135
136
```java
137
List<String> firstMock = mock(List.class);
138
List<String> secondMock = mock(List.class);
139
140
// Use mocks in specific order
141
firstMock.add("first");
142
secondMock.add("second");
143
firstMock.add("third");
144
145
// Verify order
146
InOrder inOrder = inOrder(firstMock, secondMock);
147
inOrder.verify(firstMock).add("first");
148
inOrder.verify(secondMock).add("second");
149
inOrder.verify(firstMock).add("third");
150
151
// Verify no more interactions in order
152
inOrder.verifyNoMoreInteractions();
153
```
154
155
### Mixed Order Verification
156
157
Combine ordered and unordered verification.
158
159
**Usage Example:**
160
161
```java
162
List<String> mockList = mock(List.class);
163
164
mockList.add("first");
165
mockList.size(); // Can happen anytime
166
mockList.add("second");
167
168
// Verify order for specific calls
169
InOrder inOrder = inOrder(mockList);
170
inOrder.verify(mockList).add("first");
171
inOrder.verify(mockList).add("second");
172
173
// Verify size() was called (but order doesn't matter)
174
verify(mockList).size();
175
```
176
177
## Advanced Verification
178
179
### Custom Verification Messages
180
181
Add custom descriptions to verification failures.
182
183
```java { .api }
184
interface VerificationMode {
185
VerificationMode description(String description);
186
}
187
```
188
189
**Usage Examples:**
190
191
```java
192
List<String> mockList = mock(List.class);
193
194
// Verification with custom error message
195
verify(mockList, times(1).description("Should add exactly one item"))
196
.add(anyString());
197
198
// Timeout with description
199
verify(mockCallback, timeout(1000).description("Callback should complete within 1 second"))
200
.onComplete(any());
201
```
202
203
### Argument Capture for Verification
204
205
Capture arguments for detailed assertions after verification.
206
207
```java { .api }
208
public static <T> ArgumentCaptor<T> captor(Class<T> clazz)
209
210
class ArgumentCaptor<T> {
211
public static <T> ArgumentCaptor<T> forClass(Class<T> clazz);
212
public T capture();
213
public List<T> getAllValues();
214
public T getValue();
215
}
216
```
217
218
**Usage Examples:**
219
220
```java
221
List<String> mockList = mock(List.class);
222
223
// Use mock
224
mockList.add("first");
225
mockList.add("second");
226
227
// Capture arguments
228
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
229
verify(mockList, times(2)).add(captor.capture());
230
231
// Assert on captured values
232
List<String> capturedValues = captor.getAllValues();
233
assertEquals("first", capturedValues.get(0));
234
assertEquals("second", capturedValues.get(1));
235
236
// Or just the last captured value
237
assertEquals("second", captor.getValue());
238
```
239
240
### Ignoring Stubs for Verification
241
242
Verify only interactions that weren't stubbed.
243
244
```java { .api }
245
public static Object[] ignoreStubs(Object... mocks)
246
```
247
248
**Usage Example:**
249
250
```java
251
List<String> mockList = mock(List.class);
252
253
// Stub method
254
when(mockList.get(0)).thenReturn("stubbed");
255
256
// Use mock
257
mockList.get(0); // This is stubbed
258
mockList.add("item"); // This is not stubbed
259
260
// Verify ignoring stubbed interactions
261
verify(ignoreStubs(mockList)).add("item");
262
verifyNoMoreInteractions(ignoreStubs(mockList));
263
```
264
265
## Verification Exception Types
266
267
### Common Verification Exceptions
268
269
Understanding verification failure exceptions.
270
271
```java { .api }
272
class WantedButNotInvoked extends MockitoAssertionError {
273
// Thrown when expected method call didn't happen
274
}
275
276
class TooManyActualInvocations extends MockitoAssertionError {
277
// Thrown when method called more times than expected
278
}
279
280
class ArgumentsAreDifferent extends MockitoAssertionError {
281
// Thrown when method called with different arguments
282
}
283
284
class NoInteractionsWanted extends MockitoAssertionError {
285
// Thrown when verifyNoInteractions() fails
286
}
287
```
288
289
**Handling Verification Failures:**
290
291
```java
292
try {
293
verify(mockList).add("expected");
294
} catch (WantedButNotInvoked e) {
295
// Handle case where method wasn't called
296
System.out.println("Method not called: " + e.getMessage());
297
}
298
299
try {
300
verify(mockList, never()).clear();
301
} catch (MockitoAssertionError e) {
302
// Handle verification failure
303
System.out.println("Verification failed: " + e.getMessage());
304
}
305
```
306
307
## Verification Best Practices
308
309
### BDD-Style Verification
310
311
Using then() for behavior-driven testing (covered in detail in BDD section).
312
313
```java { .api }
314
public static <T> Then<T> then(T mock)
315
316
interface Then<T> {
317
BDDInOrder<T> should();
318
BDDInOrder<T> should(VerificationMode mode);
319
BDDInOrder<T> shouldHaveNoInteractions();
320
BDDInOrder<T> shouldHaveNoMoreInteractions();
321
}
322
```
323
324
**Usage Example:**
325
326
```java
327
// BDD-style verification
328
then(mockList).should().add("item");
329
then(mockList).should(times(2)).add(anyString());
330
then(mockList).shouldHaveNoMoreInteractions();
331
```