0
# Enhanced Object Mocking
1
2
PowerMock extends Mockito's object mocking capabilities to handle final classes, final methods, and native methods that cannot be mocked with standard Mockito. This enables comprehensive testing of legacy code without requiring architectural changes.
3
4
## Capabilities
5
6
### Basic Enhanced Mocking
7
8
Create mocks of classes that cannot be mocked with standard Mockito, including final classes and classes with final methods.
9
10
```java { .api }
11
static <T> T mock(Class<T> type);
12
```
13
14
**Parameters:**
15
- `type` - The class to mock (can be final)
16
17
**Returns:** Mock instance of the specified type
18
19
**Usage Example:**
20
```java
21
@Test
22
@PrepareForTest(FinalClass.class)
23
public void testFinalClassMocking() {
24
FinalClass mock = mock(FinalClass.class);
25
when(mock.getValue()).thenReturn("mocked value");
26
27
String result = mock.getValue();
28
assertEquals("mocked value", result);
29
30
verify(mock).getValue();
31
}
32
```
33
34
### Mocking with Custom Answer
35
36
Create enhanced mocks with a custom default answer strategy for unstubbed method calls.
37
38
```java { .api }
39
static <T> T mock(Class<T> classToMock, Answer defaultAnswer);
40
```
41
42
**Parameters:**
43
- `classToMock` - The class to mock
44
- `defaultAnswer` - Default answer strategy for unstubbed methods
45
46
**Returns:** Mock instance with custom default behavior
47
48
**Usage Example:**
49
```java
50
@Test
51
@PrepareForTest(ServiceClass.class)
52
public void testMockWithCustomAnswer() {
53
ServiceClass mock = mock(ServiceClass.class, RETURNS_SMART_NULLS);
54
55
// Only stub specific method
56
when(mock.getImportantValue()).thenReturn("important");
57
58
String important = mock.getImportantValue(); // Returns "important"
59
String other = mock.getOtherValue(); // Returns smart null
60
}
61
```
62
63
### Mocking with Settings
64
65
Create enhanced mocks with advanced MockSettings configuration for specialized testing scenarios.
66
67
```java { .api }
68
static <T> T mock(Class<T> classToMock, MockSettings mockSettings);
69
```
70
71
**Parameters:**
72
- `classToMock` - The class to mock
73
- `mockSettings` - Advanced mock configuration
74
75
**Returns:** Mock instance configured with specified settings
76
77
**Usage Example:**
78
```java
79
@Test
80
@PrepareForTest(ComplexService.class)
81
public void testMockWithSettings() {
82
ComplexService mock = mock(ComplexService.class,
83
withSettings()
84
.name("ComplexServiceMock")
85
.defaultAnswer(RETURNS_DEEP_STUBS)
86
.extraInterfaces(Serializable.class));
87
88
when(mock.getConfiguration().getProperty("key")).thenReturn("value");
89
90
String property = mock.getConfiguration().getProperty("key");
91
assertEquals("value", property);
92
}
93
```
94
95
### Enhanced Spying on Objects
96
97
Spy on objects that are final or otherwise not "spyable" with standard Mockito, enabling partial mocking of real objects.
98
99
```java { .api }
100
static <T> T spy(T object);
101
```
102
103
**Parameters:**
104
- `object` - The real object to spy on (can be final)
105
106
**Returns:** Spy instance that delegates to the real object unless stubbed
107
108
**Usage Example:**
109
```java
110
@Test
111
@PrepareForTest(FinalService.class)
112
public void testSpyOnFinalObject() {
113
FinalService realService = new FinalService();
114
FinalService spy = spy(realService);
115
116
// Stub one method, others call real implementation
117
when(spy.getValue()).thenReturn("spied value");
118
119
String value = spy.getValue(); // Returns "spied value"
120
String realResult = spy.calculateSomething(); // Calls real method
121
122
verify(spy).getValue();
123
verify(spy).calculateSomething();
124
}
125
```
126
127
### Enhanced Class Spying
128
129
Enable spying on static methods of a class, allowing partial mocking of static behavior.
130
131
```java { .api }
132
static <T> void spy(Class<T> type);
133
```
134
135
**Parameters:**
136
- `type` - The class to enable static spying for
137
138
**Usage Example:**
139
```java
140
@Test
141
@PrepareForTest(UtilityClass.class)
142
public void testSpyOnClass() {
143
spy(UtilityClass.class);
144
145
// Stub one static method, others call real implementation
146
when(UtilityClass.getValue()).thenReturn("spied static value");
147
148
String value = UtilityClass.getValue(); // Returns "spied static value"
149
int realResult = UtilityClass.calculate(5, 3); // Calls real method
150
151
verifyStatic(UtilityClass.class);
152
UtilityClass.getValue();
153
}
154
```
155
156
## Common Patterns
157
158
### Testing Final Third-Party Classes
159
160
```java
161
@Test
162
@PrepareForTest(HttpURLConnection.class)
163
public void testFinalThirdPartyClass() {
164
HttpURLConnection connection = mock(HttpURLConnection.class);
165
when(connection.getResponseCode()).thenReturn(200);
166
when(connection.getInputStream()).thenReturn(new ByteArrayInputStream("response".getBytes()));
167
168
// Test code that uses the mocked connection
169
MyHttpClient client = new MyHttpClient();
170
String response = client.makeRequest(connection);
171
172
assertEquals("response", response);
173
verify(connection).getResponseCode();
174
}
175
```
176
177
### Partial Mocking of Legacy Objects
178
179
```java
180
@Test
181
@PrepareForTest(LegacyService.class)
182
public void testPartialMocking() {
183
LegacyService service = new LegacyService();
184
LegacyService spy = spy(service);
185
186
// Mock only the problematic dependency method
187
when(spy.callExternalService()).thenReturn("mocked external response");
188
189
// Test the main business logic with mocked dependency
190
String result = spy.processData("input");
191
192
// Verify the external call was made but returned mocked value
193
verify(spy).callExternalService();
194
assertTrue(result.contains("mocked external response"));
195
}
196
```
197
198
### Mocking Classes with Native Methods
199
200
```java
201
@Test
202
@PrepareForTest(SystemClass.class)
203
public void testNativeMethodMocking() {
204
SystemClass mock = mock(SystemClass.class);
205
206
// Mock native method that would normally fail in test environment
207
when(mock.nativeSystemCall()).thenReturn("mocked native result");
208
209
ApplicationService service = new ApplicationService(mock);
210
service.performSystemOperation();
211
212
verify(mock).nativeSystemCall();
213
}
214
```
215
216
## Requirements
217
218
- Final classes must be specified in `@PrepareForTest` annotation
219
- Test must use `@RunWith(PowerMockRunner.class)` or equivalent
220
- Enhanced mocking works with all standard Mockito verification and stubbing
221
- Spies maintain real object behavior unless explicitly stubbed