0
# Mock Creation and Static Mocking
1
2
PowerMock's mock creation capabilities extend beyond standard Mockito to support final classes, static methods, and advanced spying scenarios. This comprehensive system handles traditionally challenging mocking scenarios through bytecode manipulation.
3
4
## Mock Creation
5
6
### Basic Mock Creation
7
8
Create mocks that support final and native methods that standard Mockito cannot handle.
9
10
```java { .api }
11
public static <T> T mock(Class<T> type);
12
```
13
14
Creates a mock object with default behavior for the specified type.
15
16
**Usage Example:**
17
```java
18
// Mock a final class
19
FinalClass mockFinal = mock(FinalClass.class);
20
when(mockFinal.someMethod()).thenReturn("mocked");
21
22
// Mock works even with final methods
23
String result = mockFinal.someMethod();
24
assertEquals("mocked", result);
25
```
26
27
### Mock with Custom Answer
28
29
```java { .api }
30
public static <T> T mock(Class<T> classToMock, Answer defaultAnswer);
31
```
32
33
Creates a mock with a specified default answer strategy for unstubbed method calls.
34
35
**Parameters:**
36
- `classToMock` - The class or interface to mock
37
- `defaultAnswer` - Default answer for unstubbed methods (e.g., `RETURNS_SMART_NULLS`, `CALLS_REAL_METHODS`)
38
39
**Usage Example:**
40
```java
41
import static org.mockito.Mockito.RETURNS_SMART_NULLS;
42
43
MyClass mock = mock(MyClass.class, RETURNS_SMART_NULLS);
44
// Unstubbed methods will return smart nulls instead of null
45
```
46
47
### Mock with Settings
48
49
```java { .api }
50
public static <T> T mock(Class<T> classToMock, MockSettings mockSettings);
51
```
52
53
Creates a mock with custom mock settings for advanced configuration.
54
55
**Parameters:**
56
- `classToMock` - The class or interface to mock
57
- `mockSettings` - Configuration settings created with `Mockito.withSettings()`
58
59
**Usage Example:**
60
```java
61
import static org.mockito.Mockito.withSettings;
62
63
UserService mock = mock(UserService.class,
64
withSettings()
65
.name("userServiceMock")
66
.defaultAnswer(RETURNS_SMART_NULLS)
67
.serializable());
68
```
69
70
## Static Mocking
71
72
### Basic Static Mocking
73
74
Enable static method mocking for one or more classes.
75
76
```java { .api }
77
public static void mockStatic(Class<?> type, Class<?>... types);
78
```
79
80
Enables static mocking for the specified classes. Once enabled, all static methods become mockable.
81
82
**Parameters:**
83
- `type` - Primary class to enable static mocking for
84
- `types` - Additional classes to enable static mocking for (varargs)
85
86
**Usage Example:**
87
```java
88
// Enable static mocking for utility classes
89
mockStatic(FileUtils.class, StringUtils.class);
90
91
// Now static methods can be stubbed
92
when(FileUtils.readFile("test.txt")).thenReturn("file content");
93
when(StringUtils.isEmpty(anyString())).thenReturn(false);
94
95
// Use the mocked static methods
96
String content = FileUtils.readFile("test.txt");
97
boolean empty = StringUtils.isEmpty("test");
98
99
assertEquals("file content", content);
100
assertFalse(empty);
101
```
102
103
### Static Mocking with Answer
104
105
```java { .api }
106
public static void mockStatic(Class<?> classMock, Answer defaultAnswer);
107
```
108
109
Enables static mocking with a custom default answer for unstubbed static methods.
110
111
**Usage Example:**
112
```java
113
mockStatic(MathUtils.class, RETURNS_SMART_NULLS);
114
// Unstubbed static methods will return smart nulls
115
```
116
117
### Static Mocking with Settings
118
119
```java { .api }
120
public static void mockStatic(Class<?> classToMock, MockSettings mockSettings);
121
```
122
123
Enables static mocking with custom mock settings.
124
125
**Usage Example:**
126
```java
127
mockStatic(Logger.class,
128
withSettings()
129
.name("loggerMock")
130
.defaultAnswer(CALLS_REAL_METHODS));
131
```
132
133
## Spying
134
135
### Object Spying
136
137
Spy on objects that are final or otherwise not "spyable" with standard Mockito.
138
139
```java { .api }
140
public static <T> T spy(T object);
141
```
142
143
Creates a spy of the given object, allowing partial mocking where some methods can be stubbed while others call the real implementation.
144
145
**Parameters:**
146
- `object` - The object to spy on
147
148
**Usage Example:**
149
```java
150
List<String> realList = new ArrayList<>();
151
realList.add("original");
152
153
List<String> spyList = spy(realList);
154
155
// Stub specific methods
156
when(spyList.size()).thenReturn(100);
157
158
// Real methods still work
159
spyList.add("new item");
160
161
assertEquals(100, spyList.size()); // stubbed
162
assertTrue(spyList.contains("new item")); // real method
163
```
164
165
### Class Spying
166
167
Create a spy for an entire class, enabling static method spying.
168
169
```java { .api }
170
public static <T> void spy(Class<T> type);
171
```
172
173
Enables spying on static methods of the specified class. Similar to static mocking but calls real methods by default.
174
175
**Parameters:**
176
- `type` - The class to enable spying for
177
178
**Usage Example:**
179
```java
180
spy(DatabaseUtils.class);
181
182
// Spy on specific static methods while leaving others unchanged
183
doReturn("mocked connection").when(DatabaseUtils.class);
184
DatabaseUtils.getConnection();
185
186
// Verify static method calls
187
verifyStatic(DatabaseUtils.class);
188
DatabaseUtils.getConnection();
189
```
190
191
## Advanced Usage Patterns
192
193
### Combining Mock Types
194
195
```java
196
// Create regular mock
197
UserService userService = mock(UserService.class);
198
199
// Enable static mocking
200
mockStatic(SecurityUtils.class);
201
202
// Create spy for partial mocking
203
OrderProcessor processor = spy(new OrderProcessor());
204
205
// Use all together
206
when(userService.getUser(1L)).thenReturn(testUser);
207
when(SecurityUtils.hasPermission(anyString())).thenReturn(true);
208
doNothing().when(processor).logOrder(any());
209
```
210
211
### Mock Settings Combinations
212
213
```java
214
DatabaseService dbMock = mock(DatabaseService.class,
215
withSettings()
216
.name("dbServiceMock")
217
.defaultAnswer(RETURNS_SMART_NULLS)
218
.extraInterfaces(Closeable.class)
219
.serializable());
220
```
221
222
### Error Handling
223
224
PowerMock mock creation may throw `ClassNotPreparedException` if the class hasn't been properly prepared for mocking:
225
226
```java
227
try {
228
mockStatic(SomeUtility.class);
229
} catch (ClassNotPreparedException e) {
230
// Class wasn't prepared for mocking - check @PrepareForTest annotation
231
fail("Class not prepared for mocking: " + e.getMessage());
232
}
233
```