PowerMock API extension for Mockito that enables mocking of static methods, constructors, final classes and methods, private methods, and advanced testing capabilities through bytecode manipulation and custom classloading
npx @tessl/cli install tessl/maven-org-powermock--powermock-api-mockito@1.7.00
# PowerMock API for Mockito
1
2
PowerMock API extension for Mockito that enables mocking of static methods, constructors, final classes and methods, private methods, and advanced testing capabilities through bytecode manipulation and custom classloading. It extends Mockito's capabilities to handle traditionally "untestable" code patterns found in legacy systems.
3
4
## Package Information
5
6
- **Package Name**: org.powermock:powermock-api-mockito
7
- **Package Type**: Maven
8
- **Language**: Java
9
- **Installation**: Add to Maven dependencies:
10
```xml
11
<dependency>
12
<groupId>org.powermock</groupId>
13
<artifactId>powermock-api-mockito</artifactId>
14
<version>1.7.4</version>
15
<scope>test</scope>
16
</dependency>
17
```
18
19
## Core Imports
20
21
```java
22
import static org.powermock.api.mockito.PowerMockito.*;
23
```
24
25
Individual imports:
26
```java
27
import org.powermock.api.mockito.PowerMockito;
28
import org.powermock.api.mockito.PowerMockitoStubber;
29
import org.powermock.api.mockito.verification.PrivateMethodVerification;
30
import org.powermock.api.mockito.verification.ConstructorArgumentsVerification;
31
```
32
33
## Basic Usage
34
35
```java
36
import static org.powermock.api.mockito.PowerMockito.*;
37
import org.junit.Test;
38
import org.junit.runner.RunWith;
39
import org.powermock.core.classloader.annotations.PrepareForTest;
40
import org.powermock.modules.junit4.PowerMockRunner;
41
42
@RunWith(PowerMockRunner.class)
43
@PrepareForTest({StaticUtility.class, FinalClass.class})
44
public class PowerMockExampleTest {
45
46
@Test
47
public void testStaticMethodMocking() {
48
// Mock static methods
49
mockStatic(StaticUtility.class);
50
when(StaticUtility.getValue()).thenReturn("mocked");
51
52
// Use the mocked static method
53
String result = StaticUtility.getValue();
54
assertEquals("mocked", result);
55
56
// Verify static method was called
57
verifyStatic(StaticUtility.class);
58
StaticUtility.getValue();
59
}
60
61
@Test
62
public void testConstructorMocking() throws Exception {
63
// Mock constructor calls
64
whenNew(FileReader.class).withArguments("test.txt")
65
.thenThrow(new IOException("File not found"));
66
67
// Verify constructor was called
68
verifyNew(FileReader.class).withArguments("test.txt");
69
}
70
71
@Test
72
public void testPrivateMethodStubbing() throws Exception {
73
MyService service = spy(new MyService());
74
75
// Stub private method
76
when(service, "validateInput", "test").thenReturn(true);
77
78
// Test behavior that uses the private method
79
boolean result = service.processInput("test");
80
assertTrue(result);
81
82
// Verify private method was called
83
verifyPrivate(service).invoke("validateInput", "test");
84
}
85
}
86
```
87
88
## Architecture
89
90
PowerMock extends Mockito through several key components:
91
92
- **PowerMockito**: Main static facade providing enhanced mocking capabilities
93
- **Mock Creation**: Custom mock creators that bypass Java's limitations on final classes
94
- **Bytecode Manipulation**: CGLIB-based enhancement for method interception
95
- **ClassLoader Control**: Custom classloading to enable mocking of system classes
96
- **Expectation Framework**: Fluent API for setting up complex mock behaviors
97
- **Verification System**: Enhanced verification for private methods and constructors
98
99
This architecture enables testing of legacy code that would otherwise be untestable with standard Mockito, including static methods, final classes, constructors, and private methods.
100
101
## Capabilities
102
103
### Static Method Mocking
104
105
Mock static methods on classes to control their behavior in tests, enabling isolation of code that depends on static utilities, system calls, or third-party static APIs.
106
107
```java { .api }
108
static void mockStatic(Class<?> type, Class<?>... types);
109
static void mockStatic(Class<?> classMock, Answer defaultAnswer);
110
static void mockStatic(Class<?> classToMock, MockSettings mockSettings);
111
```
112
113
[Static Method Mocking](./static-mocking.md)
114
115
### Enhanced Object Mocking
116
117
Create mocks of final classes, final methods, and native methods that cannot be mocked with standard Mockito, while maintaining full compatibility with Mockito's API.
118
119
```java { .api }
120
static <T> T mock(Class<T> type);
121
static <T> T mock(Class<T> classToMock, Answer defaultAnswer);
122
static <T> T mock(Class<T> classToMock, MockSettings mockSettings);
123
static <T> T spy(T object);
124
static <T> void spy(Class<T> type);
125
```
126
127
[Enhanced Object Mocking](./object-mocking.md)
128
129
### Private Method Testing
130
131
Stub and verify private method calls on both instance and static methods, enabling comprehensive testing of internal implementation details when necessary.
132
133
```java { .api }
134
static <T> OngoingStubbing<T> when(Object instance, String methodName, Object... arguments) throws Exception;
135
static <T> WithOrWithoutExpectedArguments<T> when(Object instance, Method method) throws Exception;
136
static <T> WithOrWithoutExpectedArguments<T> when(Class<?> cls, Method method) throws Exception;
137
static PrivateMethodVerification verifyPrivate(Object object) throws Exception;
138
static PrivateMethodVerification verifyPrivate(Object object, VerificationMode verificationMode) throws Exception;
139
```
140
141
[Private Method Testing](./private-methods.md)
142
143
### Constructor Mocking
144
145
Mock constructor calls to control object creation, enabling testing of code that creates objects internally without dependency injection.
146
147
```java { .api }
148
static <T> ConstructorExpectationSetup<T> whenNew(Class<T> type);
149
static <T> WithOrWithoutExpectedArguments<T> whenNew(Constructor<T> ctor);
150
static <T> ConstructorExpectationSetup<T> whenNew(String fullyQualifiedName) throws Exception;
151
static <T> ConstructorArgumentsVerification verifyNew(Class<T> mock);
152
static <T> ConstructorArgumentsVerification verifyNew(Class<?> mock, VerificationMode mode);
153
```
154
155
[Constructor Mocking](./constructor-mocking.md)
156
157
### Static Method Verification
158
159
Verify that static methods were called with expected arguments and frequencies, providing the same verification capabilities for static methods as Mockito provides for instance methods.
160
161
```java { .api }
162
static <T> void verifyStatic(Class<T> mockedClass);
163
static <T> void verifyStatic(Class<T> mockedClass, VerificationMode verificationMode);
164
```
165
166
[Static Method Verification](./static-verification.md)
167
168
### Advanced Stubbing
169
170
Enhanced stubbing capabilities for void methods, private methods, and methods that cannot be handled by standard Mockito when() syntax.
171
172
```java { .api }
173
static PowerMockitoStubber doAnswer(Answer<?> answer);
174
static PowerMockitoStubber doThrow(Throwable toBeThrown);
175
static PowerMockitoStubber doCallRealMethod();
176
static PowerMockitoStubber doNothing();
177
static PowerMockitoStubber doReturn(Object toBeReturned);
178
static PowerMockitoStubber doReturn(Object toBeReturned, Object... othersToBeReturned);
179
```
180
181
[Advanced Stubbing](./advanced-stubbing.md)
182
183
### Verification Extensions
184
185
Enhanced verification methods that work with PowerMock's advanced mocking capabilities, including verification of interactions with static methods and private methods.
186
187
```java { .api }
188
static void verifyNoMoreInteractions(Object... mocks);
189
static void verifyZeroInteractions(Object... mocks);
190
```
191
192
[Verification Extensions](./verification-extensions.md)
193
194
## Types
195
196
```java { .api }
197
interface PowerMockitoStubber extends Stubber {
198
void when(Class<?> classMock);
199
<T> PrivatelyExpectedArguments when(T mock, Method method) throws Exception;
200
<T> void when(T mock, Object... arguments) throws Exception;
201
<T> void when(T mock, String methodToExpected, Object... arguments) throws Exception;
202
<T> PrivatelyExpectedArguments when(Class<T> classMock, Method method) throws Exception;
203
<T> void when(Class<T> classMock, Object... arguments) throws Exception;
204
<T> void when(Class<T> classMock, String methodToExpected, Object... parameters) throws Exception;
205
}
206
207
interface PrivateMethodVerification {
208
void invoke(Object... arguments) throws Exception;
209
WithOrWithoutVerifiedArguments invoke(Method method) throws Exception;
210
void invoke(String methodToVerify, Object... arguments) throws Exception;
211
}
212
213
interface ConstructorArgumentsVerification {
214
void withArguments(Object argument, Object... additionalArguments) throws Exception;
215
void withNoArguments() throws Exception;
216
}
217
218
interface ConstructorExpectationSetup<T> extends WithOrWithoutExpectedArguments<T>, WithExpectedParameterTypes<T>, WithAnyArguments<T> {
219
}
220
221
interface WithOrWithoutExpectedArguments<T> extends WithExpectedArguments<T>, WithoutExpectedArguments<T> {
222
}
223
224
interface WithExpectedArguments<T> {
225
OngoingStubbing<T> withArguments(Object firstArgument, Object... additionalArguments) throws Exception;
226
}
227
228
interface WithoutExpectedArguments<T> {
229
OngoingStubbing<T> withNoArguments() throws Exception;
230
}
231
232
interface WithExpectedParameterTypes<T> {
233
WithExpectedArguments<T> withParameterTypes(Class<?> parameterType, Class<?>... additionalParameterTypes);
234
}
235
236
interface WithAnyArguments<T> {
237
OngoingStubbing<T> withAnyArguments() throws Exception;
238
}
239
240
interface PrivatelyExpectedArguments {
241
<T> void withArguments(Object firstArgument, Object... additionalArguments) throws Exception;
242
<T> void withNoArguments() throws Exception;
243
}
244
245
interface WithOrWithoutVerifiedArguments extends WithVerifiedArguments, WithoutVerifiedArguments {
246
}
247
248
interface WithVerifiedArguments {
249
void withArguments(Object firstArgument, Object... additionalArguments) throws Exception;
250
}
251
252
interface WithoutVerifiedArguments {
253
void withNoArguments() throws Exception;
254
}
255
```