0
# Static Method Mocking
1
2
PowerMock's static method mocking capabilities enable testing of code that depends on static method calls. This is essential for testing legacy code, third-party libraries, and system interactions that rely on static APIs.
3
4
## Capabilities
5
6
### Basic Static Mocking
7
8
Enable mocking for all static methods in a class or specific static methods only.
9
10
```java { .api }
11
/**
12
* Enable static mocking for a class.
13
*
14
* @param type the class to enable static mocking
15
* @param methods optionally what methods to mock
16
*/
17
public static synchronized void mockStatic(Class<?> type, Method... methods);
18
19
/**
20
* Enable static mocking for a class.
21
*
22
* @param type the class to enable static mocking
23
*/
24
public static synchronized void mockStatic(Class<?> type);
25
```
26
27
#### Usage Example
28
29
```java
30
import org.powermock.api.easymock.PowerMock;
31
import org.powermock.core.classloader.annotations.PrepareForTest;
32
import static org.easymock.EasyMock.expect;
33
34
@PrepareForTest({SystemUtils.class})
35
public class StaticMockingTest {
36
37
@Test
38
public void testStaticMethod() {
39
// Mock all static methods in SystemUtils
40
PowerMock.mockStatic(SystemUtils.class);
41
expect(SystemUtils.getCurrentUser()).andReturn("testuser");
42
expect(SystemUtils.getSystemProperty("os.name")).andReturn("TestOS");
43
PowerMock.replayAll();
44
45
// Test code that calls static methods
46
String user = MyApplication.getCurrentUserInfo();
47
assertEquals("User: testuser on TestOS", user);
48
49
PowerMock.verifyAll();
50
}
51
}
52
```
53
54
### Strict Static Mocking
55
56
Enable strict static mocking that verifies the order of static method calls.
57
58
```java { .api }
59
/**
60
* Enable strict static mocking for a class.
61
*
62
* @param type the class to enable static mocking
63
* @param methods optionally what methods to mock
64
*/
65
public static synchronized void mockStaticStrict(Class<?> type, Method... methods);
66
67
/**
68
* Enable strict static mocking for a class.
69
*
70
* @param type the class to enable static mocking
71
*/
72
public static synchronized void mockStaticStrict(Class<?> type);
73
```
74
75
#### Usage Example
76
77
```java
78
@Test
79
public void testStaticMethodOrder() {
80
PowerMock.mockStaticStrict(FileUtils.class);
81
expect(FileUtils.createTempDirectory()).andReturn("/tmp/test");
82
expect(FileUtils.writeFile("/tmp/test/data.txt", "content")).andReturn(true);
83
expect(FileUtils.deleteDirectory("/tmp/test")).andReturn(true);
84
PowerMock.replayAll();
85
86
// These static calls must happen in exactly this order
87
String tempDir = FileUtils.createTempDirectory();
88
FileUtils.writeFile(tempDir + "/data.txt", "content");
89
FileUtils.deleteDirectory(tempDir);
90
91
PowerMock.verifyAll();
92
}
93
```
94
95
### Nice Static Mocking
96
97
Enable nice static mocking that provides default return values for unexpected static method calls.
98
99
```java { .api }
100
/**
101
* Enable nice static mocking for a class.
102
*
103
* @param type the class to enable static mocking
104
* @param methods optionally what methods to mock
105
*/
106
public static synchronized void mockStaticNice(Class<?> type, Method... methods);
107
108
/**
109
* Enable nice static mocking for a class.
110
*
111
* @param type the class to enable static mocking
112
*/
113
public static synchronized void mockStaticNice(Class<?> type);
114
```
115
116
#### Usage Example
117
118
```java
119
@Test
120
public void testNiceStaticMocking() {
121
PowerMock.mockStaticNice(MathUtils.class);
122
// Only set up the static methods you care about
123
expect(MathUtils.square(5)).andReturn(25);
124
PowerMock.replayAll();
125
126
// This call has explicit expectation
127
int result = MathUtils.square(5); // Returns 25
128
assertEquals(25, result);
129
130
// These calls don't have expectations but work with nice mock
131
double pi = MathUtils.getPi(); // Returns 0.0 (default for double)
132
boolean isEven = MathUtils.isEven(4); // Returns false (default for boolean)
133
134
PowerMock.verifyAll();
135
}
136
```
137
138
### Partial Static Mocking
139
140
Mock specific static methods by name, leaving other static methods with their original behavior.
141
142
```java { .api }
143
/**
144
* Mock several static methods by name.
145
*
146
* @param clazz the class that contains the static methods
147
* @param methodNames the names of the methods that should be mocked
148
*/
149
public static synchronized void mockStaticPartial(Class<?> clazz, String... methodNames);
150
151
/**
152
* Mock several static methods (strict) by name.
153
*
154
* @param clazz the class that contains the static methods
155
* @param methodNames the names of the methods that should be mocked
156
*/
157
public static synchronized void mockStaticPartialStrict(Class<?> clazz, String... methodNames);
158
159
/**
160
* Mock several static methods (nice) by name.
161
*
162
* @param clazz the class that contains the static methods
163
* @param methodNames the names of the methods that should be mocked
164
*/
165
public static synchronized void mockStaticPartialNice(Class<?> clazz, String... methodNames);
166
```
167
168
#### Usage Example
169
170
```java
171
@Test
172
public void testPartialStaticMocking() {
173
// Only mock specific static methods by name
174
PowerMock.mockStaticPartial(DateUtils.class, "getCurrentTimestamp", "formatDate");
175
176
expect(DateUtils.getCurrentTimestamp()).andReturn(1234567890L);
177
expect(DateUtils.formatDate(anyObject(Date.class))).andReturn("2023-01-01");
178
PowerMock.replayAll();
179
180
// Mocked static methods
181
long timestamp = DateUtils.getCurrentTimestamp(); // Returns 1234567890L
182
String formatted = DateUtils.formatDate(new Date()); // Returns "2023-01-01"
183
184
// Non-mocked static methods retain original behavior
185
Date parsed = DateUtils.parseDate("2023-01-01"); // Uses real implementation
186
187
PowerMock.verifyAll();
188
}
189
```
190
191
### Specific Static Method Mocking
192
193
Mock specific static methods with parameter type specification for overloaded methods.
194
195
```java { .api }
196
/**
197
* Mock a single static method.
198
*
199
* @param clazz the class where the method is specified
200
* @param methodNameToMock the method name to mock
201
* @param firstArgumentType the first argument type
202
* @param additionalArgumentTypes optional additional argument types
203
*/
204
public static synchronized void mockStaticPartial(Class<?> clazz, String methodNameToMock,
205
Class<?> firstArgumentType, Class<?>... additionalArgumentTypes);
206
207
/**
208
* Mock a single static method (strict).
209
*
210
* @param clazz the class where the method is specified
211
* @param methodNameToMock the method name to mock
212
* @param firstArgumentType the first argument type
213
* @param additionalArgumentTypes optional additional argument types
214
*/
215
public static synchronized void mockStaticPartialStrict(Class<?> clazz, String methodNameToMock,
216
Class<?> firstArgumentType, Class<?>... additionalArgumentTypes);
217
218
/**
219
* Mock a single static method (nice).
220
*
221
* @param clazz the class where the method is specified
222
* @param methodNameToMock the method name to mock
223
* @param firstArgumentType the first argument type
224
* @param additionalArgumentTypes optional additional argument types
225
*/
226
public static synchronized void mockStaticPartialNice(Class<?> clazz, String methodNameToMock,
227
Class<?> firstArgumentType, Class<?>... additionalArgumentTypes);
228
```
229
230
#### Usage Example
231
232
```java
233
@Test
234
public void testOverloadedStaticMethods() {
235
// Mock specific overloaded static method
236
PowerMock.mockStaticPartial(StringUtils.class, "join", List.class, String.class);
237
238
List<String> items = Arrays.asList("a", "b", "c");
239
expect(StringUtils.join(items, ",")).andReturn("a,b,c");
240
PowerMock.replayAll();
241
242
// This overloaded version is mocked
243
String result = StringUtils.join(items, ","); // Returns "a,b,c"
244
assertEquals("a,b,c", result);
245
246
// Other overloaded versions retain original behavior
247
String result2 = StringUtils.join(new String[]{"x", "y"}, "-"); // Uses real implementation
248
249
PowerMock.verifyAll();
250
}
251
```
252
253
## Important Notes
254
255
### PrepareForTest Annotation
256
257
Classes with static methods being mocked must be specified in the `@PrepareForTest` annotation:
258
259
```java
260
@RunWith(PowerMockRunner.class)
261
@PrepareForTest({SystemUtils.class, FileUtils.class})
262
public class MyTest {
263
// Static mocking tests
264
}
265
```
266
267
### Replay and Verify
268
269
Static mocks must be included in replay and verify operations:
270
271
```java
272
// Include the class in replay/verify
273
PowerMock.mockStatic(SystemUtils.class);
274
expect(SystemUtils.getProperty("key")).andReturn("value");
275
PowerMock.replay(SystemUtils.class); // Replay the class, not instance
276
277
// Or use replayAll() to replay all mocks including static ones
278
PowerMock.replayAll();
279
```
280
281
### Thread Safety
282
283
Static mocking affects the entire JVM class loading, so tests using static mocks should be run in isolation or with careful coordination to avoid interference between tests.