0
# Mock Control and Lifecycle
1
2
PowerMock provides comprehensive control over mock behavior through replay/verify cycles and state management. These capabilities enable sophisticated testing scenarios with multiple mocks, bulk operations, and integration with EasyMock's control mechanisms.
3
4
## Capabilities
5
6
### Bulk Mock Operations
7
8
Control all PowerMock-managed mocks with single method calls.
9
10
```java { .api }
11
/**
12
* Replay all classes and mock objects known by PowerMock.
13
*
14
* @param additionalMocks mocks not created by PowerMock API to include in replay
15
*/
16
public static synchronized void replayAll(Object... additionalMocks);
17
18
/**
19
* Verify all classes and mock objects known by PowerMock.
20
*/
21
public static synchronized void verifyAll();
22
23
/**
24
* Reset all classes and mock objects known by PowerMock.
25
*
26
* @param additionalMocks mocks not created by PowerMock API to include in reset
27
*/
28
public static synchronized void resetAll(Object... additionalMocks);
29
```
30
31
#### Usage Example
32
33
```java
34
import org.powermock.api.easymock.PowerMock;
35
import org.powermock.core.classloader.annotations.PrepareForTest;
36
37
@PrepareForTest({FileUtils.class, DatabaseService.class})
38
public class BulkMockControlTest {
39
40
@Test
41
public void testBulkMockOperations() throws Exception {
42
// Create various types of mocks
43
UserService userService = PowerMock.createMock(UserService.class);
44
PowerMock.mockStatic(FileUtils.class);
45
PowerMock.expectNew(DatabaseService.class, "localhost").andReturn(mockDbService);
46
47
// Set up expectations for all mocks
48
expect(userService.getUserById(1)).andReturn(new User("john"));
49
expect(FileUtils.readFile("config.txt")).andReturn("config data");
50
expect(mockDbService.connect()).andReturn(true);
51
52
// Replay all mocks at once
53
PowerMock.replayAll();
54
55
// Test your code that uses all these mocks
56
ApplicationService appService = new ApplicationService();
57
String result = appService.processUser(1);
58
59
assertEquals("Processed user john with config data", result);
60
61
// Verify all mocks at once
62
PowerMock.verifyAll();
63
}
64
}
65
```
66
67
### Individual Mock Control
68
69
Control specific mock objects and classes individually.
70
71
```java { .api }
72
/**
73
* Switches mocks or classes to replay mode.
74
*
75
* @param mocks mock objects or classes loaded by PowerMock
76
* @throws RuntimeException if something unexpected goes wrong
77
*/
78
public static synchronized void replay(Object... mocks);
79
80
/**
81
* Switches mocks or classes to verify mode.
82
*
83
* @param objects mock objects or classes loaded by PowerMock
84
*/
85
public static synchronized void verify(Object... objects);
86
87
/**
88
* Reset a list of mock objects or classes.
89
*
90
* @param mocks mock objects or classes to reset
91
*/
92
public static synchronized void reset(Object... mocks);
93
```
94
95
#### Usage Example
96
97
```java
98
@Test
99
public void testIndividualMockControl() {
100
UserService userService = PowerMock.createMock(UserService.class);
101
OrderService orderService = PowerMock.createMock(OrderService.class);
102
103
// Set up expectations
104
expect(userService.getUserById(1)).andReturn(new User("alice"));
105
expect(orderService.getOrdersByUser(1)).andReturn(Arrays.asList(new Order("order1")));
106
107
// Replay specific mocks
108
PowerMock.replay(userService, orderService);
109
110
// Test code
111
User user = userService.getUserById(1);
112
List<Order> orders = orderService.getOrdersByUser(1);
113
114
assertEquals("alice", user.getName());
115
assertEquals(1, orders.size());
116
117
// Verify specific mocks
118
PowerMock.verify(userService, orderService);
119
}
120
```
121
122
### EasyMock Integration
123
124
Use standard EasyMock expectation methods with PowerMock-created mocks.
125
126
```java { .api }
127
/**
128
* This method delegates to EasyMock's expectLastCall() method.
129
*
130
* @return the expectation setter
131
*/
132
public static synchronized IExpectationSetters<Object> expectLastCall();
133
```
134
135
#### Usage Example
136
137
```java
138
@Test
139
public void testEasyMockIntegration() {
140
Logger logger = PowerMock.createMock(Logger.class);
141
142
// Void method expectation using expectLastCall
143
logger.info("Starting process");
144
PowerMock.expectLastCall().times(2); // Expect this call twice
145
146
logger.error("Process failed");
147
PowerMock.expectLastCall().andThrow(new RuntimeException("Logging system down"));
148
149
PowerMock.replay(logger);
150
151
// First two calls succeed
152
logger.info("Starting process");
153
logger.info("Starting process");
154
155
// Third call throws exception
156
try {
157
logger.error("Process failed");
158
fail("Expected exception");
159
} catch (RuntimeException e) {
160
assertEquals("Logging system down", e.getMessage());
161
}
162
163
PowerMock.verify(logger);
164
}
165
```
166
167
### Nice Replay and Verify Mode
168
169
Enable lenient mode for tests that use both mocks and non-mock objects.
170
171
```java { .api }
172
/**
173
* Sometimes it is useful to allow replay and verify on non-mocks.
174
* For example when using partial mocking in some tests and no mocking in other test methods.
175
*/
176
public static synchronized void niceReplayAndVerify();
177
```
178
179
#### Usage Example
180
181
```java
182
@Test
183
public void testNiceReplayAndVerify() {
184
// Enable nice mode for mixed mock/non-mock scenarios
185
PowerMock.niceReplayAndVerify();
186
187
UserService mockUserService = PowerMock.createMock(UserService.class);
188
OrderService realOrderService = new OrderService(); // Real object, not a mock
189
190
expect(mockUserService.getUserById(1)).andReturn(new User("bob"));
191
192
PowerMock.replayAll();
193
194
// Test code that uses both mocks and real objects
195
User user = mockUserService.getUserById(1);
196
List<Order> orders = realOrderService.getOrdersByUser(1); // Real method call
197
198
// verifyAll() won't fail on the real object in nice mode
199
PowerMock.verifyAll();
200
}
201
```
202
203
## Advanced Mock Control Patterns
204
205
### Sequential Mock State Management
206
207
Control mock states through multiple test phases.
208
209
```java
210
@Test
211
public void testSequentialMockStates() {
212
DatabaseConnection connection = PowerMock.createMock(DatabaseConnection.class);
213
214
// Phase 1: Initial expectations
215
expect(connection.connect()).andReturn(true);
216
expect(connection.executeQuery("SELECT 1")).andReturn("1");
217
PowerMock.replay(connection);
218
219
// Execute phase 1
220
assertTrue(connection.connect());
221
assertEquals("1", connection.executeQuery("SELECT 1"));
222
PowerMock.verify(connection);
223
224
// Reset for phase 2
225
PowerMock.reset(connection);
226
expect(connection.executeQuery("SELECT 2")).andReturn("2");
227
expect(connection.disconnect()).andReturn(true);
228
PowerMock.replay(connection);
229
230
// Execute phase 2
231
assertEquals("2", connection.executeQuery("SELECT 2"));
232
assertTrue(connection.disconnect());
233
PowerMock.verify(connection);
234
}
235
```
236
237
### Mixed Mock Types Control
238
239
Manage different types of mocks (instance, static, constructor) together.
240
241
```java
242
@PrepareForTest({FileUtils.class, MyService.class})
243
@Test
244
public void testMixedMockTypes() throws Exception {
245
// Instance mock
246
Logger logger = PowerMock.createMock(Logger.class);
247
248
// Static mock
249
PowerMock.mockStatic(FileUtils.class);
250
251
// Constructor mock
252
DatabaseConnection mockConnection = PowerMock.createMock(DatabaseConnection.class);
253
PowerMock.expectNew(DatabaseConnection.class, "localhost").andReturn(mockConnection);
254
255
// Set up all expectations
256
logger.info("Processing started");
257
PowerMock.expectLastCall();
258
expect(FileUtils.readFile("input.txt")).andReturn("file content");
259
expect(mockConnection.isConnected()).andReturn(true);
260
261
// Control all mocks together
262
PowerMock.replayAll();
263
264
// Test code using all mock types
265
MyService service = new MyService(logger);
266
String result = service.processFile("input.txt"); // Uses all three mock types
267
268
assertEquals("Processed: file content", result);
269
PowerMock.verifyAll();
270
}
271
```
272
273
### Conditional Mock Control
274
275
Apply different control strategies based on test conditions.
276
277
```java
278
@Test
279
public void testConditionalMockControl() {
280
boolean useStrictMode = true;
281
282
UserService userService;
283
if (useStrictMode) {
284
userService = PowerMock.createStrictMock(UserService.class);
285
// Strict mode requires exact order
286
expect(userService.validateUser("john")).andReturn(true);
287
expect(userService.getUserDetails("john")).andReturn(new UserDetails("john", "admin"));
288
} else {
289
userService = PowerMock.createNiceMock(UserService.class);
290
// Nice mode allows any order
291
expect(userService.validateUser("john")).andReturn(true);
292
expect(userService.getUserDetails("john")).andReturn(new UserDetails("john", "admin"));
293
}
294
295
PowerMock.replay(userService);
296
297
// Test code - order matters in strict mode
298
boolean valid = userService.validateUser("john");
299
UserDetails details = userService.getUserDetails("john");
300
301
assertTrue(valid);
302
assertEquals("admin", details.getRole());
303
304
PowerMock.verify(userService);
305
}
306
```
307
308
### Exception Handling in Mock Control
309
310
Handle exceptions during mock control operations.
311
312
```java
313
@Test
314
public void testMockControlExceptionHandling() {
315
List<Object> mocks = new ArrayList<>();
316
317
try {
318
UserService userService = PowerMock.createMock(UserService.class);
319
OrderService orderService = PowerMock.createMock(OrderService.class);
320
mocks.addAll(Arrays.asList(userService, orderService));
321
322
// Set up expectations that might fail
323
expect(userService.getUserById(1)).andReturn(new User("test"));
324
expect(orderService.getOrdersByUser(1)).andThrow(new ServiceException("Database error"));
325
326
PowerMock.replay(userService, orderService);
327
328
// Test code
329
User user = userService.getUserById(1);
330
try {
331
orderService.getOrdersByUser(1);
332
fail("Expected ServiceException");
333
} catch (ServiceException e) {
334
assertEquals("Database error", e.getMessage());
335
}
336
337
PowerMock.verify(userService, orderService);
338
339
} catch (Exception e) {
340
// Clean up mocks if test fails
341
if (!mocks.isEmpty()) {
342
PowerMock.reset(mocks.toArray());
343
}
344
throw e;
345
}
346
}
347
```
348
349
## Best Practices
350
351
### Test Setup and Teardown
352
353
```java
354
public class MockControlBestPracticesTest {
355
private UserService userService;
356
private OrderService orderService;
357
358
@Before
359
public void setUp() {
360
userService = PowerMock.createMock(UserService.class);
361
orderService = PowerMock.createMock(OrderService.class);
362
}
363
364
@After
365
public void tearDown() {
366
// Reset all mocks after each test
367
PowerMock.resetAll();
368
}
369
370
@Test
371
public void testWithCleanSetup() {
372
// Test implementation - mocks are clean from setUp()
373
expect(userService.getUserById(1)).andReturn(new User("clean"));
374
PowerMock.replayAll();
375
376
User user = userService.getUserById(1);
377
assertEquals("clean", user.getName());
378
379
PowerMock.verifyAll();
380
// tearDown() will reset mocks automatically
381
}
382
}
383
```
384
385
### Verification Error Handling
386
387
```java
388
@Test
389
public void testVerificationWithErrorHandling() {
390
Calculator calculator = PowerMock.createStrictMock(Calculator.class);
391
392
expect(calculator.add(5, 3)).andReturn(8);
393
expect(calculator.multiply(8, 2)).andReturn(16);
394
PowerMock.replay(calculator);
395
396
// Perform operations
397
int sum = calculator.add(5, 3);
398
399
try {
400
PowerMock.verify(calculator);
401
fail("Should have failed - multiply not called");
402
} catch (AssertionError e) {
403
// Expected - multiply method was not called
404
assertTrue(e.getMessage().contains("multiply"));
405
}
406
407
// Complete the expected interactions
408
int product = calculator.multiply(8, 2);
409
PowerMock.verify(calculator); // Now passes
410
}
411
```
412
413
## Important Notes
414
415
### Mock Lifecycle
416
417
1. **Create** - Create mocks using PowerMock factory methods
418
2. **Setup** - Configure expectations using `expect()` and `expectLastCall()`
419
3. **Replay** - Switch to replay mode using `replay()` or `replayAll()`
420
4. **Execute** - Run the code under test
421
5. **Verify** - Check expectations using `verify()` or `verifyAll()`
422
6. **Reset** - Clean up for next test using `reset()` or `resetAll()`
423
424
### Thread Safety
425
426
Mock control operations are synchronized but the mocks themselves are not thread-safe. Avoid sharing mocks across concurrent test execution.
427
428
### Integration with Test Frameworks
429
430
PowerMock mock control integrates seamlessly with JUnit, TestNG, and other testing frameworks through proper setup and teardown methods.