0
# Stubbing
1
2
PowerMock's stubbing system extends Mockito's capabilities with the PowerMockitoStubber interface, enabling advanced stubbing scenarios for void methods, private methods, static methods, and complex stubbing patterns that standard Mockito cannot handle.
3
4
## Basic Stubbing Methods
5
6
### Answer-Based Stubbing
7
8
Stub methods to execute custom Answer implementations.
9
10
```java { .api }
11
public static PowerMockitoStubber doAnswer(Answer<?> answer);
12
```
13
14
Configure methods to execute custom logic when called, useful for complex return value computation or side effects.
15
16
**Parameters:**
17
- `answer` - Custom Answer implementation defining the stubbing behavior
18
19
**Returns:**
20
- `PowerMockitoStubber` - Extended stubber for PowerMock-specific stubbing scenarios
21
22
**Usage Example:**
23
```java
24
UserService service = spy(new UserService());
25
26
doAnswer(invocation -> {
27
String username = invocation.getArgument(0);
28
if ("admin".equals(username)) {
29
return "Administrator User";
30
}
31
return "Regular User";
32
}).when(service, "getDisplayName", anyString());
33
34
String adminName = service.getDisplayName("admin");
35
String userNmae = service.getDisplayName("john");
36
37
assertEquals("Administrator User", adminName);
38
assertEquals("Regular User", userNmae);
39
```
40
41
### Exception Stubbing
42
43
Stub methods to throw specific exceptions.
44
45
```java { .api }
46
public static PowerMockitoStubber doThrow(Throwable toBeThrown);
47
```
48
49
Configure methods to throw exceptions when called, essential for testing error handling scenarios.
50
51
**Usage Example:**
52
```java
53
DatabaseService dbService = spy(new DatabaseService());
54
55
doThrow(new SQLException("Connection timeout"))
56
.when(dbService, "executeQuery", anyString());
57
58
// Test error handling
59
try {
60
dbService.executeQuery("SELECT * FROM users");
61
fail("Expected SQLException");
62
} catch (SQLException e) {
63
assertEquals("Connection timeout", e.getMessage());
64
}
65
```
66
67
### Real Method Calling
68
69
Stub methods to call their real implementations.
70
71
```java { .api }
72
public static PowerMockitoStubber doCallRealMethod();
73
```
74
75
Configure mocked methods to execute their actual implementation, useful for partial mocking scenarios.
76
77
**Usage Example:**
78
```java
79
Calculator calculator = mock(Calculator.class);
80
81
// Most methods are mocked, but allow real implementation for basic operations
82
doCallRealMethod().when(calculator).add(anyInt(), anyInt());
83
84
// Mock complex operations
85
when(calculator.complexCalculation(anyDouble())).thenReturn(42.0);
86
87
int result = calculator.add(5, 3); // calls real method, returns 8
88
double complex = calculator.complexCalculation(100); // returns mocked value 42.0
89
```
90
91
### Do Nothing Stubbing
92
93
Stub void methods to do nothing.
94
95
```java { .api }
96
public static PowerMockitoStubber doNothing();
97
```
98
99
Explicitly configure void methods to do nothing, useful for consecutive stubbing or spy scenarios.
100
101
**Usage Example:**
102
```java
103
Logger logger = spy(new Logger());
104
105
// First call does nothing, second call throws exception
106
doNothing()
107
.doThrow(new RuntimeException("Logging failed"))
108
.when(logger).log(anyString());
109
110
logger.log("First message"); // does nothing
111
try {
112
logger.log("Second message"); // throws exception
113
} catch (RuntimeException e) {
114
assertEquals("Logging failed", e.getMessage());
115
}
116
```
117
118
### Return Value Stubbing
119
120
Stub methods to return specific values.
121
122
```java { .api }
123
public static PowerMockitoStubber doReturn(Object toBeReturned);
124
public static PowerMockitoStubber doReturn(Object toBeReturned, Object... othersToBeReturned);
125
```
126
127
Configure methods to return specific values, essential when `when().thenReturn()` cannot be used (e.g., with spies that would execute real methods).
128
129
**Parameters:**
130
- `toBeReturned` - First value to return
131
- `othersToBeReturned` - Additional values for consecutive calls
132
133
**Usage Examples:**
134
```java
135
FileService fileService = spy(new FileService());
136
137
// Single return value
138
doReturn("file content")
139
.when(fileService, "readPrivateFile", "/secret/config.txt");
140
141
// Multiple consecutive return values
142
doReturn("first", "second", "third")
143
.when(fileService, "getNextLine");
144
145
String content = fileService.readPrivateFile("/secret/config.txt"); // "file content"
146
String line1 = fileService.getNextLine(); // "first"
147
String line2 = fileService.getNextLine(); // "second"
148
String line3 = fileService.getNextLine(); // "third"
149
```
150
151
## PowerMockitoStubber Interface
152
153
The PowerMockitoStubber extends Mockito's Stubber with PowerMock-specific capabilities:
154
155
```java { .api }
156
interface PowerMockitoStubber extends Stubber {
157
void when(Class<?> classMock);
158
<T> PrivatelyExpectedArguments when(T mock, Method method) throws Exception;
159
<T> void when(T mock, Object... arguments) throws Exception;
160
<T> void when(T mock, String methodToExpect, Object... arguments) throws Exception;
161
<T> PrivatelyExpectedArguments when(Class<T> classMock, Method method) throws Exception;
162
<T> void when(Class<T> classMock, Object... arguments) throws Exception;
163
<T> void when(Class<T> classMock, String methodToExpect, Object... arguments) throws Exception;
164
}
165
```
166
167
## Stubbing Static Methods
168
169
### Basic Static Method Stubbing
170
171
```java { .api }
172
void when(Class<?> classMock);
173
```
174
175
Select a static method for stubbing using the standard method call syntax.
176
177
**Usage Example:**
178
```java
179
mockStatic(FileUtils.class);
180
181
doReturn("mocked content")
182
.when(FileUtils.class);
183
FileUtils.readFile("config.txt");
184
185
String content = FileUtils.readFile("config.txt");
186
assertEquals("mocked content", content);
187
```
188
189
## Stubbing Private Instance Methods
190
191
### Private Method Stubbing with Method Objects
192
193
```java { .api }
194
<T> PrivatelyExpectedArguments when(T mock, Method method) throws Exception;
195
```
196
197
Stub private instance methods using Method objects for precise identification.
198
199
**Usage Example:**
200
```java
201
UserService service = spy(new UserService());
202
Method privateMethod = PowerMockito.method(UserService.class, "encryptPassword", String.class);
203
204
doReturn("encrypted_password")
205
.when(service, privateMethod)
206
.withArguments("plaintext");
207
```
208
209
### Private Method Stubbing by Arguments
210
211
```java { .api }
212
<T> void when(T mock, Object... arguments) throws Exception;
213
```
214
215
Stub private methods by providing arguments that PowerMock uses to identify the target method.
216
217
**Usage Example:**
218
```java
219
Calculator calc = spy(new Calculator());
220
221
doReturn(100.0)
222
.when(calc, 10.0, 5.0); // PowerMock finds private method(double, double)
223
224
doThrow(new IllegalArgumentException())
225
.when(calc, "invalid"); // PowerMock finds private method(String)
226
```
227
228
### Private Method Stubbing by Name
229
230
```java { .api }
231
<T> void when(T mock, String methodToExpected, Object... arguments) throws Exception;
232
```
233
234
Stub private methods by explicitly specifying the method name and arguments.
235
236
**Usage Example:**
237
```java
238
DataProcessor processor = spy(new DataProcessor());
239
240
doAnswer(invocation -> {
241
String data = invocation.getArgument(0);
242
return data.toUpperCase();
243
}).when(processor, "transformData", anyString());
244
245
// Execute code that calls private transformData method
246
String result = processor.processInput("hello world");
247
assertEquals("HELLO WORLD", result);
248
```
249
250
## Stubbing Static Private Methods
251
252
### Static Private Method with Method Objects
253
254
```java { .api }
255
<T> PrivatelyExpectedArguments when(Class<T> classMock, Method method) throws Exception;
256
```
257
258
**Usage Example:**
259
```java
260
Method staticPrivateMethod = PowerMockito.method(CryptoUtils.class, "generateSalt", int.class);
261
262
doReturn("generated_salt")
263
.when(CryptoUtils.class, staticPrivateMethod)
264
.withArguments(32);
265
```
266
267
### Static Private Method by Arguments
268
269
```java { .api }
270
<T> void when(Class<T> classMock, Object... arguments) throws Exception;
271
```
272
273
**Usage Example:**
274
```java
275
doReturn("computed_hash")
276
.when(HashUtils.class, "secretData", 256);
277
```
278
279
### Static Private Method by Name
280
281
```java { .api }
282
<T> void when(Class<T> classMock, String methodToExpected, Object... arguments) throws Exception;
283
```
284
285
**Usage Example:**
286
```java
287
doThrow(new SecurityException("Access denied"))
288
.when(SecurityUtils.class, "checkInternalPermission", "admin");
289
```
290
291
## PrivatelyExpectedArguments Interface
292
293
Interface for specifying arguments when stubbing private methods with Method objects:
294
295
```java { .api }
296
interface PrivatelyExpectedArguments {
297
<T> void withArguments(Object firstArgument, Object... additionalArguments) throws Exception;
298
<T> void withNoArguments() throws Exception;
299
}
300
```
301
302
**Usage Examples:**
303
```java
304
Method privateMethod = PowerMockito.method(Service.class, "helper", String.class, int.class);
305
306
// Specific arguments
307
doReturn("result")
308
.when(service, privateMethod)
309
.withArguments("test", 42);
310
311
// No arguments
312
doNothing()
313
.when(service, privateMethod)
314
.withNoArguments();
315
```
316
317
## Advanced Stubbing Patterns
318
319
### Consecutive Stubbing
320
321
```java
322
UserService service = spy(new UserService());
323
324
// Different behaviors for consecutive calls
325
doReturn(true)
326
.doReturn(false)
327
.doThrow(new RuntimeException("Max attempts exceeded"))
328
.when(service, "authenticate", anyString(), anyString());
329
330
boolean result1 = service.authenticate("user", "pass"); // true
331
boolean result2 = service.authenticate("user", "pass"); // false
332
// Third call throws exception
333
```
334
335
### Conditional Stubbing
336
337
```java
338
DatabaseService dbService = spy(new DatabaseService());
339
340
doAnswer(invocation -> {
341
String query = invocation.getArgument(0);
342
if (query.contains("DROP")) {
343
throw new SecurityException("DROP operations not allowed");
344
}
345
return "Query executed successfully";
346
}).when(dbService, "executeQuery", anyString());
347
```
348
349
### Argument Matchers in Stubbing
350
351
```java
352
import static org.mockito.ArgumentMatchers.*;
353
354
// Use argument matchers for flexible stubbing
355
doReturn("admin_result")
356
.when(service, "processRequest", eq("admin"), any());
357
358
doThrow(new IllegalArgumentException())
359
.when(validator, "validate", argThat(data -> data.length() < 5));
360
```
361
362
### Error Handling in Stubbing
363
364
```java
365
try {
366
doReturn("value")
367
.when(service, "nonExistentMethod", "param");
368
} catch (Exception e) {
369
// Handle cases where method doesn't exist or isn't accessible
370
logger.warn("Stubbing setup failed: " + e.getMessage());
371
}
372
```
373
374
### Combining Stubbing with Verification
375
376
```java
377
EmailService emailService = spy(new EmailService());
378
379
// Stub private method
380
doNothing()
381
.when(emailService, "logEmail", anyString());
382
383
// Execute code under test
384
emailService.sendNotification("user@example.com", "message");
385
386
// Verify private method was called
387
verifyPrivate(emailService).invoke("logEmail", contains("user@example.com"));
388
```
389
390
## Member Introspection for Stubbing
391
392
PowerMock provides powerful member introspection utilities for finding methods by name, parameter types, or class hierarchy traversal. These are essential for precise private method stubbing.
393
394
### Method Finding by Name and Parameters
395
396
```java { .api }
397
public static Method method(Class<?> declaringClass, String methodName, Class<?>... parameterTypes);
398
```
399
400
Find a specific method by name and exact parameter types.
401
402
**Usage Example:**
403
```java
404
// Find specific private method for stubbing
405
Method privateMethod = PowerMockito.method(UserService.class, "encryptPassword", String.class);
406
407
doReturn("encrypted_password")
408
.when(userService, privateMethod)
409
.withArguments("plaintext");
410
```
411
412
### Method Finding by Parameters Only
413
414
```java { .api }
415
public static Method method(Class<?> declaringClass, Class<?>... parameterTypes);
416
```
417
418
Find a method by parameter types alone (useful when method name is unique by parameters).
419
420
**Usage Example:**
421
```java
422
// Find method by parameter signature
423
Method uniqueMethod = PowerMockito.method(CryptoService.class, String.class, byte[].class);
424
425
doThrow(new CryptoException())
426
.when(cryptoService, uniqueMethod)
427
.withArguments(anyString(), any(byte[].class));
428
```
429
430
### Multiple Method Finding
431
432
```java { .api }
433
public static Method[] methods(Class<?> clazz, String methodName, String... additionalMethodNames);
434
```
435
436
Get multiple methods by names for batch stubbing operations.
437
438
**Usage Example:**
439
```java
440
// Find multiple methods for comprehensive stubbing
441
Method[] authMethods = PowerMockito.methods(AuthService.class, "authenticate", "authorize", "validate");
442
443
for (Method method : authMethods) {
444
doReturn(true)
445
.when(authService, method)
446
.withArguments(any());
447
}
448
```
449
450
### Class Hierarchy Method Discovery
451
452
```java { .api }
453
public static Method[] methodsDeclaredIn(Class<?> cls, Class<?>... additionalClasses);
454
```
455
456
Get all methods from a class hierarchy for comprehensive stubbing.
457
458
**Usage Example:**
459
```java
460
// Get all methods from service and its parent classes
461
Method[] allMethods = PowerMockito.methodsDeclaredIn(UserService.class, BaseService.class);
462
463
// Stub all void methods to do nothing
464
for (Method method : allMethods) {
465
if (method.getReturnType() == void.class) {
466
doNothing().when(userService, method);
467
}
468
}
469
```