0
# Constructor and New Object Mocking
1
2
PowerMock's constructor mocking capabilities enable controlling object instantiation during testing. This is essential for testing code that creates objects internally, depends on specific constructor behavior, or needs to avoid expensive object creation.
3
4
## Capabilities
5
6
### Basic Constructor Expectations
7
8
Set up expectations for constructor calls with automatic parameter matching.
9
10
```java { .api }
11
/**
12
* Allows specifying expectations on new invocations.
13
*
14
* @param type the class type being constructed
15
* @param arguments the constructor arguments
16
* @return expectation setter for further configuration
17
* @throws Exception if constructor cannot be found or invoked
18
*/
19
public static synchronized <T> IExpectationSetters<T> expectNew(Class<T> type, Object... arguments) throws Exception;
20
21
/**
22
* Allows specifying expectations on new invocations with explicit parameter types.
23
*
24
* @param type the class type being constructed
25
* @param parameterTypes the constructor parameter types
26
* @param arguments the constructor arguments
27
* @return expectation setter for further configuration
28
* @throws Exception if constructor cannot be found or invoked
29
*/
30
public static synchronized <T> IExpectationSetters<T> expectNew(Class<T> type, Class<?>[] parameterTypes, Object... arguments) throws Exception;
31
32
/**
33
* Allows specifying expectations on new invocations using fully qualified class name.
34
*
35
* @param fullyQualifiedName the fully qualified class name being constructed
36
* @param arguments the constructor arguments
37
* @return expectation setter for further configuration
38
* @throws Exception if class cannot be found or constructor cannot be invoked
39
*/
40
public static synchronized <T> IExpectationSetters<T> expectNew(String fullyQualifiedName, Object... arguments) throws Exception;
41
```
42
43
#### Usage Example
44
45
```java
46
import org.powermock.api.easymock.PowerMock;
47
import org.powermock.core.classloader.annotations.PrepareForTest;
48
49
@PrepareForTest({DatabaseService.class}) // Prepare the class that creates new objects
50
public class ConstructorMockingTest {
51
52
@Test
53
public void testConstructorMocking() throws Exception {
54
// Create a mock to return instead of real object
55
DatabaseConnection mockConnection = PowerMock.createMock(DatabaseConnection.class);
56
57
// Set up constructor expectation
58
PowerMock.expectNew(DatabaseConnection.class, "localhost", 5432)
59
.andReturn(mockConnection);
60
61
// Set up mock behavior
62
expect(mockConnection.connect()).andReturn(true);
63
expect(mockConnection.executeQuery("SELECT 1")).andReturn("result");
64
65
PowerMock.replayAll();
66
67
// Test code that creates new DatabaseConnection("localhost", 5432)
68
DatabaseService service = new DatabaseService();
69
String result = service.testConnection(); // Internally creates DatabaseConnection
70
71
assertEquals("Connection successful: result", result);
72
PowerMock.verifyAll();
73
}
74
}
75
```
76
77
### Constructor Expectations for Overloaded Constructors
78
79
Handle classes with multiple constructors by specifying exact parameter types.
80
81
```java
82
@Test
83
public void testOverloadedConstructors() throws Exception {
84
FileProcessor mockProcessor = PowerMock.createMock(FileProcessor.class);
85
86
// Specify exact constructor signature for overloaded constructors
87
Class<?>[] paramTypes = {String.class, boolean.class, int.class};
88
PowerMock.expectNew(FileProcessor.class, paramTypes, "input.txt", true, 1024)
89
.andReturn(mockProcessor);
90
91
expect(mockProcessor.process()).andReturn("processed");
92
PowerMock.replayAll();
93
94
// Code that creates: new FileProcessor("input.txt", true, 1024)
95
DocumentHandler handler = new DocumentHandler();
96
String result = handler.processDocument("input.txt");
97
98
assertEquals("processed", result);
99
PowerMock.verifyAll();
100
}
101
```
102
103
### Strict Constructor Expectations
104
105
Set up strict constructor expectations that verify the order of object creation.
106
107
```java { .api }
108
/**
109
* Allows specifying strict expectations on new invocations.
110
*
111
* @param type the class type being constructed
112
* @param arguments the constructor arguments
113
* @return expectation setter for further configuration
114
* @throws Exception if constructor cannot be found or invoked
115
*/
116
public static synchronized <T> IExpectationSetters<T> expectStrictNew(Class<T> type, Object... arguments) throws Exception;
117
118
/**
119
* Allows specifying strict expectations on new invocations with explicit parameter types.
120
*
121
* @param type the class type being constructed
122
* @param parameterTypes the constructor parameter types
123
* @param arguments the constructor arguments
124
* @return expectation setter for further configuration
125
* @throws Exception if constructor cannot be found or invoked
126
*/
127
public static synchronized <T> IExpectationSetters<T> expectStrictNew(Class<T> type, Class<?>[] parameterTypes, Object... arguments) throws Exception;
128
```
129
130
#### Usage Example
131
132
```java
133
@Test
134
public void testStrictConstructorOrder() throws Exception {
135
Logger mockLogger = PowerMock.createMock(Logger.class);
136
Metrics mockMetrics = PowerMock.createMock(Metrics.class);
137
138
// Strict expectations verify constructor call order
139
PowerMock.expectStrictNew(Logger.class, "application.log").andReturn(mockLogger);
140
PowerMock.expectStrictNew(Metrics.class, mockLogger).andReturn(mockMetrics);
141
142
PowerMock.replayAll();
143
144
// These constructor calls must happen in exactly this order
145
ApplicationService service = new ApplicationService(); // Creates Logger first, then Metrics
146
147
PowerMock.verifyAll();
148
}
149
```
150
151
### Nice Constructor Expectations
152
153
Set up lenient constructor expectations that allow unexpected constructor calls.
154
155
```java { .api }
156
/**
157
* Allows specifying nice expectations on new invocations.
158
*
159
* @param type the class type being constructed
160
* @param arguments the constructor arguments
161
* @return expectation setter for further configuration
162
* @throws Exception if constructor cannot be found or invoked
163
*/
164
public static synchronized <T> IExpectationSetters<T> expectNiceNew(Class<T> type, Object... arguments) throws Exception;
165
166
/**
167
* Allows specifying nice expectations on new invocations with explicit parameter types.
168
*
169
* @param type the class type being constructed
170
* @param parameterTypes the constructor parameter types
171
* @param arguments the constructor arguments
172
* @return expectation setter for further configuration
173
* @throws Exception if constructor cannot be found or invoked
174
*/
175
public static synchronized <T> IExpectationSetters<T> expectNiceNew(Class<T> type, Class<?>[] parameterTypes, Object... arguments) throws Exception;
176
```
177
178
#### Usage Example
179
180
```java
181
@Test
182
public void testNiceConstructorExpectations() throws Exception {
183
ConfigManager mockConfig = PowerMock.createMock(ConfigManager.class);
184
185
// Nice expectation allows unexpected constructor calls
186
PowerMock.expectNiceNew(ConfigManager.class, "app.properties").andReturn(mockConfig);
187
188
PowerMock.replayAll();
189
190
// This constructor call is expected
191
ConfigManager config1 = new ConfigManager("app.properties");
192
193
// These constructor calls are not explicitly expected but allowed with nice mock
194
ConfigManager config2 = new ConfigManager("other.properties"); // Returns null by default
195
ConfigManager config3 = new ConfigManager(); // Returns null by default
196
197
PowerMock.verifyAll();
198
}
199
```
200
201
### Convenience Methods for Mock and Expect
202
203
Combine mock creation with constructor expectation in a single method call.
204
205
```java { .api }
206
/**
207
* Convenience method for createMock followed by expectNew.
208
*
209
* @param type the class that should be mocked
210
* @param arguments the constructor arguments
211
* @return a mock object of the same type
212
* @throws Exception if constructor cannot be found or invoked
213
*/
214
public static synchronized <T> T createMockAndExpectNew(Class<T> type, Object... arguments) throws Exception;
215
216
/**
217
* Convenience method for createMock followed by expectNew with parameter types.
218
*
219
* @param type the class that should be mocked
220
* @param parameterTypes the constructor parameter types
221
* @param arguments the constructor arguments
222
* @return a mock object of the same type
223
* @throws Exception if constructor cannot be found or invoked
224
*/
225
public static synchronized <T> T createMockAndExpectNew(Class<T> type, Class<?>[] parameterTypes, Object... arguments) throws Exception;
226
227
/**
228
* Convenience method for createStrictMock followed by expectNew.
229
*
230
* @param type the class that should be mocked
231
* @param arguments the constructor arguments
232
* @return a mock object of the same type
233
* @throws Exception if constructor cannot be found or invoked
234
*/
235
public static synchronized <T> T createStrictMockAndExpectNew(Class<T> type, Object... arguments) throws Exception;
236
237
/**
238
* Convenience method for createNiceMock followed by expectNew.
239
*
240
* @param type the class that should be mocked
241
* @param arguments the constructor arguments
242
* @return a mock object of the same type
243
* @throws Exception if constructor cannot be found or invoked
244
*/
245
public static synchronized <T> T createNiceMockAndExpectNew(Class<T> type, Object... arguments) throws Exception;
246
```
247
248
#### Usage Example
249
250
```java
251
@Test
252
public void testConvenienceMethods() throws Exception {
253
// One-liner to create mock and set up constructor expectation
254
EmailService mockEmailService = PowerMock.createMockAndExpectNew(
255
EmailService.class, "smtp.example.com", 587);
256
257
expect(mockEmailService.sendEmail("test@example.com", "Subject", "Body"))
258
.andReturn(true);
259
260
PowerMock.replayAll();
261
262
// Code that creates new EmailService("smtp.example.com", 587)
263
NotificationManager manager = new NotificationManager();
264
boolean sent = manager.sendNotification("test@example.com", "Subject", "Body");
265
266
assertTrue(sent);
267
PowerMock.verifyAll();
268
}
269
```
270
271
### Inner and Anonymous Class Support
272
273
Mock constructor calls for inner classes, local classes, and anonymous classes using fully qualified names.
274
275
```java { .api }
276
/**
277
* Allows specifying expectations on new invocations for private member classes.
278
*
279
* @param fullyQualifiedName the fully-qualified name of the inner/local/anonymous type
280
* @param arguments the constructor arguments
281
* @return expectation setter for further configuration
282
* @throws Exception if constructor cannot be found or invoked
283
*/
284
public static synchronized <T> IExpectationSetters<T> expectNew(String fullyQualifiedName, Object... arguments) throws Exception;
285
```
286
287
#### Usage Example
288
289
```java
290
@Test
291
public void testInnerClassConstructor() throws Exception {
292
// Mock inner class constructor using fully qualified name
293
PowerMock.expectNew("com.example.OuterClass$InnerClass", "parameter")
294
.andReturn(mockInnerInstance);
295
296
PowerMock.replayAll();
297
298
// Code that creates new OuterClass.InnerClass("parameter")
299
OuterClass outer = new OuterClass();
300
outer.createInnerInstance("parameter");
301
302
PowerMock.verifyAll();
303
}
304
```
305
306
## Important Notes
307
308
### PrepareForTest Requirements
309
310
The class that contains the `new` statement (not the class being constructed) must be prepared for testing:
311
312
```java
313
// If MyService creates new DatabaseConnection(), prepare MyService
314
@PrepareForTest({MyService.class})
315
public class MyTest {
316
@Test
317
public void test() throws Exception {
318
PowerMock.expectNew(DatabaseConnection.class, "localhost").andReturn(mock);
319
// ...
320
}
321
}
322
```
323
324
### Exception Handling
325
326
Constructor expectations can throw exceptions instead of returning mocks:
327
328
```java
329
PowerMock.expectNew(DatabaseConnection.class, "invalid-host")
330
.andThrow(new ConnectionException("Cannot connect to invalid-host"));
331
```
332
333
### Multiple Constructor Calls
334
335
Handle multiple calls to the same constructor with different expectations:
336
337
```java
338
PowerMock.expectNew(TempFile.class).andReturn(mockFile1);
339
PowerMock.expectNew(TempFile.class).andReturn(mockFile2);
340
PowerMock.expectNew(TempFile.class).andThrow(new IOException("Disk full"));
341
```