0
# Verification Extensions
1
2
PowerMock extends Mockito's verification capabilities to work seamlessly with static methods, final classes, and other enhanced mocking features. These extensions ensure comprehensive verification coverage for all types of mocked interactions.
3
4
## Capabilities
5
6
### No More Interactions Verification
7
8
Verify that no additional interactions occurred on PowerMock-enhanced mocks beyond what has already been verified.
9
10
```java { .api }
11
static void verifyNoMoreInteractions(Object... mocks);
12
```
13
14
**Parameters:**
15
- `mocks` - Variable number of mock objects (both instance and class mocks) to verify
16
17
**Usage Example:**
18
```java
19
@Test
20
@PrepareForTest({DatabaseService.class, Logger.class})
21
public void testNoMoreInteractions() {
22
mockStatic(Logger.class);
23
DatabaseService dbMock = mock(DatabaseService.class);
24
when(dbMock.findUser("123")).thenReturn(mockUser);
25
26
UserService service = new UserService(dbMock);
27
User result = service.getUser("123");
28
29
// Verify expected interactions
30
verify(dbMock).findUser("123");
31
verifyStatic(Logger.class);
32
Logger.log("User retrieved: 123");
33
34
// Verify no additional interactions occurred
35
verifyNoMoreInteractions(dbMock);
36
verifyNoMoreInteractions(Logger.class);
37
}
38
```
39
40
### Zero Interactions Verification
41
42
Verify that no interactions occurred at all on the specified mocks.
43
44
```java { .api }
45
static void verifyZeroInteractions(Object... mocks);
46
```
47
48
**Parameters:**
49
- `mocks` - Variable number of mock objects to verify for zero interactions
50
51
**Usage Example:**
52
```java
53
@Test
54
@PrepareForTest({ExternalService.class, AuditLogger.class})
55
public void testZeroInteractions() {
56
mockStatic(ExternalService.class);
57
mockStatic(AuditLogger.class);
58
59
LocalService service = new LocalService();
60
service.performLocalOperation(); // Should not call external services
61
62
// Verify no external calls were made
63
verifyZeroInteractions(ExternalService.class);
64
verifyZeroInteractions(AuditLogger.class);
65
}
66
```
67
68
## Common Patterns
69
70
### Comprehensive Interaction Verification
71
72
```java
73
@Test
74
@PrepareForTest({SecurityService.class, NotificationService.class})
75
public void testComprehensiveVerification() {
76
mockStatic(SecurityService.class);
77
mockStatic(NotificationService.class);
78
EmailService emailMock = mock(EmailService.class);
79
80
when(SecurityService.isAuthorized("user123")).thenReturn(true);
81
when(emailMock.sendEmail(anyString(), anyString())).thenReturn(true);
82
83
UserManager manager = new UserManager(emailMock);
84
manager.processUserAction("user123", "update_profile");
85
86
// Verify all expected interactions
87
verifyStatic(SecurityService.class);
88
SecurityService.isAuthorized("user123");
89
90
verify(emailMock).sendEmail("user123", "Profile updated");
91
92
verifyStatic(NotificationService.class);
93
NotificationService.sendNotification("user123", "SUCCESS");
94
95
// Ensure no unexpected interactions occurred
96
verifyNoMoreInteractions(SecurityService.class, NotificationService.class, emailMock);
97
}
98
```
99
100
### Conditional Verification with Zero Interactions
101
102
```java
103
@Test
104
@PrepareForTest(AlertService.class)
105
public void testConditionalVerification() {
106
mockStatic(AlertService.class);
107
108
SystemMonitor monitor = new SystemMonitor();
109
110
// Test normal operation - no alerts should be sent
111
monitor.checkSystemHealth(95); // 95% healthy
112
verifyZeroInteractions(AlertService.class);
113
114
// Test critical condition - alert should be sent
115
monitor.checkSystemHealth(15); // 15% healthy
116
verifyStatic(AlertService.class);
117
AlertService.sendCriticalAlert(contains("System health critical"));
118
119
// Reset and verify no more interactions
120
reset(AlertService.class);
121
monitor.checkSystemHealth(85); // Back to normal
122
verifyZeroInteractions(AlertService.class);
123
}
124
```
125
126
### Mixed Mock Types Verification
127
128
```java
129
@Test
130
@PrepareForTest({FileUtils.class, DatabaseLogger.class})
131
public void testMixedMockVerification() {
132
mockStatic(FileUtils.class);
133
mockStatic(DatabaseLogger.class);
134
CacheService cacheMock = mock(CacheService.class);
135
136
when(FileUtils.readFile("config.properties")).thenReturn("app.name=TestApp");
137
when(cacheMock.get("config")).thenReturn(null);
138
139
ConfigurationManager manager = new ConfigurationManager(cacheMock);
140
manager.loadConfiguration();
141
142
// Verify interactions with all mock types
143
verifyStatic(FileUtils.class);
144
FileUtils.readFile("config.properties");
145
146
verify(cacheMock).get("config");
147
verify(cacheMock).put(eq("config"), any(Properties.class));
148
149
verifyStatic(DatabaseLogger.class);
150
DatabaseLogger.logConfigurationLoad();
151
152
// Comprehensive verification - no more interactions on any mock
153
verifyNoMoreInteractions(FileUtils.class, DatabaseLogger.class, cacheMock);
154
}
155
```
156
157
### Error Scenario Verification
158
159
```java
160
@Test
161
@PrepareForTest({ErrorReporter.class, RecoveryService.class})
162
public void testErrorScenarioVerification() {
163
mockStatic(ErrorReporter.class);
164
mockStatic(RecoveryService.class);
165
166
doThrow(new RuntimeException("System failure")).when(ErrorReporter.class);
167
ErrorReporter.reportError(anyString());
168
169
SystemService service = new SystemService();
170
171
assertThrows(SystemException.class, () -> {
172
service.performCriticalOperation();
173
});
174
175
// Verify error reporting was attempted
176
verifyStatic(ErrorReporter.class);
177
ErrorReporter.reportError(contains("Critical operation failed"));
178
179
// Verify recovery service was never called due to error reporter failure
180
verifyZeroInteractions(RecoveryService.class);
181
182
// Verify no unexpected interactions
183
verifyNoMoreInteractions(ErrorReporter.class);
184
}
185
```
186
187
### Stubbed vs Unstubbed Verification
188
189
```java
190
@Test
191
@PrepareForTest(MetricsCollector.class)
192
public void testStubbedVsUnstubbedVerification() {
193
mockStatic(MetricsCollector.class);
194
195
// Stub only specific method call
196
when(MetricsCollector.recordMetric("user.login", 1)).thenReturn(true);
197
198
AuthenticationService service = new AuthenticationService();
199
service.authenticateUser("user123");
200
201
// Verify stubbed interaction occurred
202
verifyStatic(MetricsCollector.class);
203
MetricsCollector.recordMetric("user.login", 1);
204
205
// This would fail if unstubbed methods were also called
206
verifyNoMoreInteractions(MetricsCollector.class);
207
}
208
```
209
210
### Verification with Timing Constraints
211
212
```java
213
@Test
214
@PrepareForTest({AsyncProcessor.class, NotificationQueue.class})
215
public void testAsyncVerification() throws Exception {
216
mockStatic(AsyncProcessor.class);
217
mockStatic(NotificationQueue.class);
218
219
EventHandler handler = new EventHandler();
220
handler.handleEvent("user_registered", userData);
221
222
// Verify async processing was triggered
223
verifyStatic(AsyncProcessor.class, timeout(2000));
224
AsyncProcessor.processAsync(eq("user_registered"), any());
225
226
// Wait and verify notification was queued
227
verifyStatic(NotificationQueue.class, timeout(3000));
228
NotificationQueue.enqueue(any(Notification.class));
229
230
// Verify no other interactions occurred during the timeout period
231
Thread.sleep(1000);
232
verifyNoMoreInteractions(AsyncProcessor.class, NotificationQueue.class);
233
}
234
```
235
236
### Verification Order with Multiple Mock Types
237
238
```java
239
@Test
240
@PrepareForTest({ValidationService.class, AuditService.class})
241
public void testVerificationOrder() {
242
mockStatic(ValidationService.class);
243
mockStatic(AuditService.class);
244
DatabaseMock dbMock = mock(DatabaseMock.class);
245
246
when(ValidationService.validate(any())).thenReturn(true);
247
when(dbMock.save(any())).thenReturn(true);
248
249
InOrder inOrder = inOrder(ValidationService.class, dbMock, AuditService.class);
250
251
DataService service = new DataService(dbMock);
252
service.saveData(testData);
253
254
// Verify correct order of operations
255
verifyStatic(ValidationService.class, inOrder);
256
ValidationService.validate(testData);
257
258
verify(dbMock, inOrder).save(testData);
259
260
verifyStatic(AuditService.class, inOrder);
261
AuditService.logDataSave(testData.getId());
262
263
// Verify no additional interactions after ordered sequence
264
verifyNoMoreInteractions(ValidationService.class, AuditService.class, dbMock);
265
}
266
```
267
268
## Integration with Standard Mockito Verification
269
270
PowerMock's verification extensions work seamlessly with standard Mockito verification:
271
272
```java
273
@Test
274
@PrepareForTest(StaticHelper.class)
275
public void testIntegratedVerification() {
276
mockStatic(StaticHelper.class);
277
ServiceDependency mockDep = mock(ServiceDependency.class);
278
279
when(StaticHelper.getValue()).thenReturn("static-value");
280
when(mockDep.process(anyString())).thenReturn("processed");
281
282
BusinessService service = new BusinessService(mockDep);
283
service.execute();
284
285
// Standard Mockito verification
286
verify(mockDep).process("static-value");
287
verify(mockDep, times(1)).process(anyString());
288
289
// PowerMock static verification
290
verifyStatic(StaticHelper.class);
291
StaticHelper.getValue();
292
293
// Combined verification extensions
294
verifyNoMoreInteractions(mockDep, StaticHelper.class);
295
}
296
```
297
298
## Benefits
299
300
### Comprehensive Test Coverage
301
- Ensures all mock interactions are accounted for
302
- Prevents over-mocking and unnecessary stub setup
303
- Validates that tests are focused and minimal
304
305
### Regression Detection
306
- Catches unexpected method calls introduced by code changes
307
- Identifies when refactoring changes interaction patterns
308
- Ensures test assumptions remain valid over time
309
310
### Test Maintenance
311
- Makes tests more strict and precise
312
- Reduces false positives from over-stubbing
313
- Improves test reliability and trustworthiness
314
315
## Requirements
316
317
- Works with all PowerMock-enhanced mocks (static, final, private methods)
318
- Compatible with standard Mockito verification modes and patterns
319
- Must be called after all expected verifications are complete
320
- Can be used with both class mocks and instance mocks simultaneously