0
# Expectation Setup
1
2
PowerMock's expectation setup system provides fluent interfaces for configuring mock behavior on private methods, constructors, and static methods. This comprehensive framework allows precise control over mock responses and argument matching.
3
4
## Method Expectation Setup
5
6
### Private Method Expectations by Name
7
8
Set up expectations for private method calls using method names and arguments.
9
10
```java { .api }
11
public static <T> OngoingStubbing<T> when(Object instance, String methodName, Object... arguments) throws Exception;
12
```
13
14
Configure expectations for private methods by specifying the method name and expected arguments.
15
16
**Parameters:**
17
- `instance` - The object instance containing the private method
18
- `methodName` - Name of the private method to expect
19
- `arguments` - Expected arguments for the method call
20
21
**Returns:**
22
- `OngoingStubbing<T>` - Standard Mockito stubbing interface for configuring return values
23
24
**Usage Example:**
25
```java
26
UserService userService = spy(new UserService());
27
28
// Setup expectation for private method
29
when(userService, "validatePassword", "admin123").thenReturn(true);
30
when(userService, "validatePassword", "wrong").thenReturn(false);
31
32
// Execute code that calls private methods
33
boolean result1 = userService.authenticate("admin", "admin123");
34
boolean result2 = userService.authenticate("admin", "wrong");
35
36
assertTrue(result1);
37
assertFalse(result2);
38
```
39
40
### Method Object-Based Expectations
41
42
Set up expectations using Method objects for precise method identification.
43
44
```java { .api }
45
public static <T> WithOrWithoutExpectedArguments<T> when(Object instance, Method method);
46
```
47
48
**Parameters:**
49
- `instance` - The object instance
50
- `method` - Method object obtained via reflection
51
52
**Returns:**
53
- `WithOrWithoutExpectedArguments<T>` - Fluent interface for argument specification
54
55
**Usage Example:**
56
```java
57
UserService service = spy(new UserService());
58
Method privateMethod = PowerMockito.method(UserService.class, "encryptData", String.class);
59
60
when(service, privateMethod)
61
.withArguments("sensitive")
62
.thenReturn("encrypted_sensitive");
63
```
64
65
### Static Method Expectations
66
67
Configure expectations for static private methods.
68
69
```java { .api }
70
public static <T> WithOrWithoutExpectedArguments<T> when(Class<?> cls, Method method);
71
```
72
73
**Usage Example:**
74
```java
75
Method staticPrivateMethod = PowerMockito.method(CryptoUtils.class, "generateKey", int.class);
76
77
when(CryptoUtils.class, staticPrivateMethod)
78
.withArguments(256)
79
.thenReturn("generated_key");
80
```
81
82
### Dynamic Method Resolution
83
84
Set up expectations without specifying method names, relying on argument type matching.
85
86
```java { .api }
87
public static <T> OngoingStubbing<T> when(Object instance, Object... arguments) throws Exception;
88
```
89
90
PowerMock attempts to find the private method based on the provided argument types.
91
92
**Usage Example:**
93
```java
94
Calculator calc = spy(new Calculator());
95
96
// PowerMock finds private method based on argument types
97
when(calc, 10, 5).thenReturn(15); // matches private method(int, int)
98
when(calc, "operation").thenReturn("completed"); // matches private method(String)
99
```
100
101
### Static Method Expectations by Name
102
103
Configure expectations for static private methods using method names.
104
105
```java { .api }
106
public static <T> OngoingStubbing<T> when(Class<?> clazz, String methodToExpect, Object... arguments) throws Exception;
107
public static <T> OngoingStubbing<T> when(Class<?> klass, Object... arguments) throws Exception;
108
```
109
110
**Usage Examples:**
111
```java
112
// By method name
113
when(SecurityUtils.class, "hashPassword", "secret").thenReturn("hashed_secret");
114
115
// By argument types
116
when(MathUtils.class, 42.0, 2).thenReturn(84.0);
117
```
118
119
## Constructor Expectation Setup
120
121
### Constructor-Based Expectations
122
123
Set up expectations for constructor calls using Constructor objects.
124
125
```java { .api }
126
public static <T> WithOrWithoutExpectedArguments<T> whenNew(Constructor<T> ctor);
127
```
128
129
**Parameters:**
130
- `ctor` - Constructor object to configure expectations for
131
132
**Usage Example:**
133
```java
134
Constructor<DatabaseConnection> constructor = DatabaseConnection.class.getConstructor(String.class, int.class);
135
DatabaseConnection mockConnection = mock(DatabaseConnection.class);
136
137
whenNew(constructor)
138
.withArguments("localhost", 5432)
139
.thenReturn(mockConnection);
140
141
// Code that creates new DatabaseConnection("localhost", 5432) will receive mockConnection
142
```
143
144
### Class-Based Constructor Expectations
145
146
Configure constructor expectations using class types.
147
148
```java { .api }
149
public static <T> ConstructorExpectationSetup<T> whenNew(Class<T> type);
150
```
151
152
**Parameters:**
153
- `type` - Class whose constructor should be mocked
154
155
**Returns:**
156
- `ConstructorExpectationSetup<T>` - Fluent interface for constructor argument specification
157
158
**Usage Example:**
159
```java
160
FileProcessor mockProcessor = mock(FileProcessor.class);
161
162
whenNew(FileProcessor.class)
163
.withArguments("/tmp/data.txt")
164
.thenReturn(mockProcessor);
165
166
// Any new FileProcessor("/tmp/data.txt") will return mockProcessor
167
```
168
169
### Inner Class Constructor Expectations
170
171
Handle expectations for private member classes, local classes, or anonymous classes.
172
173
```java { .api }
174
public static <T> ConstructorExpectationSetup<T> whenNew(String fullyQualifiedName) throws Exception;
175
```
176
177
**Parameters:**
178
- `fullyQualifiedName` - Fully qualified name of the inner/local/anonymous class
179
180
**Usage Example:**
181
```java
182
// Mock inner class constructor
183
whenNew("com.example.OuterClass$InnerClass")
184
.withNoArguments()
185
.thenReturn(mockInnerInstance);
186
```
187
188
## Expectation Setup Interfaces
189
190
### WithOrWithoutExpectedArguments Interface
191
192
Base interface providing argument specification options.
193
194
```java { .api }
195
interface WithOrWithoutExpectedArguments<T> extends WithExpectedArguments<T>, WithoutExpectedArguments<T> {}
196
```
197
198
### WithExpectedArguments Interface
199
200
Interface for specifying expected method arguments.
201
202
```java { .api }
203
interface WithExpectedArguments<T> {
204
OngoingStubbing<T> withArguments(Object firstArgument, Object... additionalArguments) throws Exception;
205
}
206
```
207
208
**Usage Example:**
209
```java
210
when(service, privateMethod)
211
.withArguments("param1", 42, true)
212
.thenReturn("result");
213
```
214
215
### WithoutExpectedArguments Interface
216
217
Interface for methods called without arguments.
218
219
```java { .api }
220
interface WithoutExpectedArguments<T> {
221
OngoingStubbing<T> withNoArguments() throws Exception;
222
}
223
```
224
225
**Usage Example:**
226
```java
227
// Expect no arguments
228
when(service, privateMethod)
229
.withNoArguments()
230
.thenReturn("no_args_result");
231
```
232
233
### WithAnyArguments Interface
234
235
Interface for methods called with any arguments.
236
237
```java { .api }
238
interface WithAnyArguments<T> {
239
OngoingStubbing<T> withAnyArguments() throws Exception;
240
}
241
```
242
243
**Usage Example:**
244
```java
245
// Accept any arguments
246
when(service, privateMethod)
247
.withAnyArguments()
248
.thenReturn("any_args_result");
249
```
250
251
### ConstructorExpectationSetup Interface
252
253
Comprehensive interface for constructor expectation configuration.
254
255
```java { .api }
256
interface ConstructorExpectationSetup<T> extends WithOrWithoutExpectedArguments<T>,
257
WithExpectedParameterTypes<T>, WithAnyArguments<T> {}
258
```
259
260
### WithExpectedParameterTypes Interface
261
262
Interface for specifying expected parameters by type.
263
264
```java { .api }
265
interface WithExpectedParameterTypes<T> {
266
WithExpectedArguments<T> withParameterTypes(Class<?> parameterType, Class<?>... additionalParameterTypes);
267
}
268
```
269
270
**Usage Example:**
271
```java
272
whenNew(Service.class)
273
.withParameterTypes(String.class, Integer.class)
274
.withArguments("test", 42)
275
.thenReturn(mockService);
276
```
277
278
### WithAnyArguments Interface
279
280
Interface for accepting any argument combination.
281
282
```java { .api }
283
interface WithAnyArguments<T> {
284
OngoingStubbing<T> withAnyArguments() throws Exception;
285
}
286
```
287
288
## Advanced Expectation Patterns
289
290
### Chaining Multiple Expectations
291
292
```java
293
UserService service = spy(new UserService());
294
295
// Chain multiple private method expectations
296
when(service, "validateUser", any(User.class))
297
.thenReturn(true);
298
299
when(service, "logAccess", anyString(), any(Date.class))
300
.thenReturn(null);
301
302
// Constructor expectations with different argument patterns
303
whenNew(AuditLog.class)
304
.withNoArguments()
305
.thenReturn(mockAuditLog);
306
307
whenNew(AuditLog.class)
308
.withArguments(anyString())
309
.thenReturn(mockAuditLog);
310
```
311
312
### Exception Expectations
313
314
```java
315
// Private method throwing exceptions
316
when(validator, "checkBusinessRules", invalidData)
317
.thenThrow(new ValidationException("Invalid data"));
318
319
// Constructor throwing exceptions
320
whenNew(DatabaseConnection.class)
321
.withArguments("invalid_url")
322
.thenThrow(new SQLException("Connection failed"));
323
```
324
325
### Argument Matchers in Expectations
326
327
```java
328
import static org.mockito.ArgumentMatchers.*;
329
330
// Use argument matchers for flexible expectations
331
when(service, "processData", any(DataModel.class), eq(true))
332
.thenReturn("processed");
333
334
when(calculator, "compute", gt(100), anyDouble())
335
.thenReturn(42.0);
336
337
// Constructor with argument matchers
338
whenNew(FileReader.class)
339
.withArguments(startsWith("/tmp/"), eq("UTF-8"))
340
.thenReturn(mockReader);
341
```
342
343
### Conditional Expectations
344
345
```java
346
// Different responses based on arguments
347
when(service, "authenticate", "admin", anyString())
348
.thenReturn(true);
349
350
when(service, "authenticate", "guest", anyString())
351
.thenReturn(false);
352
353
// Multiple return values
354
when(generator, "nextValue")
355
.thenReturn(1, 2, 3, 4, 5);
356
```
357
358
### Error Handling in Expectations
359
360
```java
361
try {
362
when(service, "nonExistentMethod").thenReturn("value");
363
} catch (Exception e) {
364
// Handle cases where private method doesn't exist
365
fail("Private method setup failed: " + e.getMessage());
366
}
367
```