PowerMock module for TestNG that enables mocking of static methods, constructors, final classes and methods, private methods, and removal of static initializers in TestNG-based unit tests.
npx @tessl/cli install tessl/maven-org-powermock--powermock-module-testng@2.0.00
# PowerMock TestNG Module
1
2
PowerMock module for TestNG that enables mocking of static methods, constructors, final classes and methods, private methods, and removal of static initializers in TestNG-based unit tests. This module provides seamless integration between PowerMock's advanced mocking capabilities and the TestNG testing framework.
3
4
## Package Information
5
6
- **Package Name**: org.powermock:powermock-module-testng
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**: Add to your Maven dependencies:
10
11
```xml
12
<dependency>
13
<groupId>org.powermock</groupId>
14
<artifactId>powermock-module-testng</artifactId>
15
<version>2.0.9</version>
16
<scope>test</scope>
17
</dependency>
18
```
19
20
Or Gradle:
21
22
```gradle
23
testImplementation 'org.powermock:powermock-module-testng:2.0.9'
24
```
25
26
## Core Imports
27
28
```java
29
import org.powermock.modules.testng.PowerMockObjectFactory;
30
import org.powermock.core.classloader.annotations.PrepareForTest;
31
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
32
```
33
34
For base class support (requires powermock-module-testng-common dependency):
35
36
```java
37
import org.powermock.modules.testng.PowerMockTestCase;
38
```
39
40
## Basic Usage
41
42
**Option 1: Configure PowerMockObjectFactory in TestNG Suite XML**
43
44
```xml
45
<suite name="MyTestSuite" object-factory="org.powermock.modules.testng.PowerMockObjectFactory">
46
<test name="PowerMockTests">
47
<classes>
48
<class name="com.example.MyTest"/>
49
</classes>
50
</test>
51
</suite>
52
```
53
54
**Option 2: Extend PowerMockTestCase (requires powermock-module-testng-common)**
55
56
```java
57
import org.powermock.core.classloader.annotations.PrepareForTest;
58
import org.powermock.modules.testng.PowerMockTestCase;
59
import org.testng.annotations.Test;
60
import static org.powermock.api.mockito.PowerMockito.*;
61
62
@PrepareForTest(StaticClass.class)
63
public class MyTest extends PowerMockTestCase {
64
65
@Test
66
public void testStaticMocking() throws Exception {
67
// Mock static method
68
mockStatic(StaticClass.class);
69
when(StaticClass.staticMethod()).thenReturn("mocked");
70
71
// Test code here
72
assertEquals("mocked", StaticClass.staticMethod());
73
74
// Verify static method was called
75
verifyStatic(StaticClass.class);
76
StaticClass.staticMethod();
77
}
78
}
79
```
80
81
**Option 3: Manual ObjectFactory Setup**
82
83
```java
84
import org.powermock.core.classloader.annotations.PrepareForTest;
85
import org.powermock.modules.testng.PowerMockObjectFactory;
86
import org.testng.IObjectFactory;
87
import org.testng.annotations.ObjectFactory;
88
import org.testng.annotations.Test;
89
import static org.powermock.api.mockito.PowerMockito.*;
90
91
@PrepareForTest(StaticClass.class)
92
public class MyTest {
93
94
@ObjectFactory
95
public IObjectFactory getObjectFactory() {
96
return new PowerMockObjectFactory();
97
}
98
99
@Test
100
public void testWithPowerMock() {
101
// PowerMock functionality available
102
mockStatic(StaticClass.class);
103
when(StaticClass.staticMethod()).thenReturn("mocked");
104
105
// Test code here
106
assertEquals("mocked", StaticClass.staticMethod());
107
108
// Verify
109
verifyStatic(StaticClass.class);
110
StaticClass.staticMethod();
111
}
112
}
113
```
114
115
## Architecture
116
117
The PowerMock TestNG module works by intercepting TestNG's test instance creation process:
118
119
- **PowerMockObjectFactory**: Detects PowerMock annotations and delegates to PowerMock classloader when needed
120
- **PowerMockTestCase**: Optional base class providing automatic mock lifecycle management
121
- **Internal Components**: Handle classloader creation, test proxying, and cleanup automatically
122
123
The module integrates with TestNG's object factory mechanism to enable PowerMock's bytecode manipulation capabilities while maintaining compatibility with standard TestNG tests.
124
125
## Capabilities
126
127
### Object Factory Integration
128
129
Primary integration mechanism that automatically enables PowerMock for tests with PowerMock annotations.
130
131
```java { .api }
132
public class PowerMockObjectFactory implements IObjectFactory {
133
public PowerMockObjectFactory();
134
@Override
135
public Object newInstance(Constructor constructor, Object... params);
136
}
137
```
138
139
The `PowerMockObjectFactory` automatically detects when test classes or methods are annotated with `@PrepareForTest` or `@SuppressStaticInitializationFor` and enables PowerMock classloader accordingly. For non-PowerMock tests, it uses the standard TestNG object factory.
140
141
Usage example:
142
```xml
143
<suite name="TestSuite" object-factory="org.powermock.modules.testng.PowerMockObjectFactory">
144
```
145
146
### Test Base Class
147
148
Optional base class providing automatic mock lifecycle management and PowerMock integration.
149
150
```java { .api }
151
public class PowerMockTestCase {
152
public PowerMockTestCase();
153
154
@BeforeClass
155
protected void beforePowerMockTestClass() throws Exception;
156
157
@AfterClass
158
protected void afterPowerMockTestClass() throws Exception;
159
160
@BeforeMethod
161
protected void beforePowerMockTestMethod() throws Exception;
162
163
@AfterMethod
164
protected void afterPowerMockTestMethod() throws Exception;
165
166
@ObjectFactory
167
public IObjectFactory create(ITestContext context);
168
}
169
```
170
171
**Lifecycle Methods:**
172
- `beforePowerMockTestClass()`: Clears mock repository and configures classloader context
173
- `afterPowerMockTestClass()`: Restores original classloader context
174
- `beforePowerMockTestMethod()`: Injects mock fields before each test method
175
- `afterPowerMockTestMethod()`: Clears mock fields and repository after each test method
176
- `create(ITestContext)`: Returns PowerMockObjectFactory instance for TestNG
177
178
Usage example:
179
```java
180
@PrepareForTest(MyStaticClass.class)
181
public class MyTest extends PowerMockTestCase {
182
@Test
183
public void testWithPowerMock() {
184
// PowerMock functionality automatically available
185
mockStatic(MyStaticClass.class);
186
// ... test code
187
}
188
}
189
```
190
191
### Internal Components
192
193
The module includes internal implementation classes that handle the heavy lifting:
194
195
```java { .api }
196
// Internal class referenced by PowerMockObjectFactory
197
public class PowerMockClassloaderObjectFactory implements IObjectFactory {
198
public PowerMockClassloaderObjectFactory();
199
@Override
200
public Object newInstance(Constructor constructor, Object... params);
201
}
202
```
203
204
**Note**: Internal classes are implementation details and should not be used directly. Use `PowerMockObjectFactory` or `PowerMockTestCase` for public API access.
205
206
## Configuration Options
207
208
### TestNG Suite Configuration
209
210
Configure PowerMock at the suite level to enable for all tests:
211
212
```xml
213
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
214
<suite name="PowerMockSuite" object-factory="org.powermock.modules.testng.PowerMockObjectFactory">
215
<test name="MyTests">
216
<classes>
217
<class name="com.example.StaticMockTest"/>
218
<class name="com.example.FinalClassTest"/>
219
</classes>
220
</test>
221
</suite>
222
```
223
224
### Annotation-Based Detection
225
226
PowerMock is automatically enabled when these annotations are present:
227
228
- `@PrepareForTest(ClassName.class)` - On class or method level
229
- `@SuppressStaticInitializationFor("package.ClassName")` - On class or method level
230
231
### Integration Patterns
232
233
**Pattern 1: Method-level PowerMock**
234
```java
235
import org.powermock.core.classloader.annotations.PrepareForTest;
236
import org.powermock.modules.testng.PowerMockObjectFactory;
237
import org.testng.IObjectFactory;
238
import org.testng.annotations.ObjectFactory;
239
import org.testng.annotations.Test;
240
241
public class FlexibleTest {
242
243
@ObjectFactory
244
public IObjectFactory getObjectFactory() {
245
return new PowerMockObjectFactory();
246
}
247
248
@Test
249
@PrepareForTest(StaticUtils.class)
250
public void testWithPowerMock() {
251
// PowerMock enabled for this method only
252
}
253
254
@Test
255
public void regularTest() {
256
// Standard TestNG test
257
}
258
}
259
```
260
261
**Pattern 2: Class-level PowerMock**
262
```java
263
import org.powermock.core.classloader.annotations.PrepareForTest;
264
import org.powermock.modules.testng.PowerMockObjectFactory;
265
import org.testng.IObjectFactory;
266
import org.testng.annotations.ObjectFactory;
267
268
@PrepareForTest({StaticClass1.class, StaticClass2.class})
269
public class PowerMockTest {
270
271
@ObjectFactory
272
public IObjectFactory getObjectFactory() {
273
return new PowerMockObjectFactory();
274
}
275
276
// All test methods have PowerMock enabled
277
}
278
```
279
280
**Pattern 3: Mixed approach**
281
```java
282
import org.powermock.core.classloader.annotations.PrepareForTest;
283
import org.powermock.modules.testng.PowerMockTestCase;
284
import org.testng.annotations.Test;
285
286
@PrepareForTest(CommonStaticClass.class)
287
public class MixedTest extends PowerMockTestCase {
288
@Test
289
@PrepareForTest(SpecialStaticClass.class) // Additional classes for this method
290
public void specialTest() {
291
// Both CommonStaticClass and SpecialStaticClass prepared
292
}
293
}
294
```
295
296
## Dependencies
297
298
This module requires the following dependencies to be present:
299
300
**Required (automatically included):**
301
- **powermock-core**: Core PowerMock functionality and classloader support
302
- **org.testng**: TestNG testing framework (6.9.10+)
303
304
**Optional (for additional functionality):**
305
- **powermock-module-testng-common**: Provides PowerMockTestCase base class for simpler integration
306
- **powermock-api-mockito2** or **powermock-api-easymock**: For specific mocking API support
307
308
**Transitive dependencies (handled automatically):**
309
- **powermock-reflect**: Internal reflection utilities
310
- **javassist**: Bytecode manipulation library
311
- **objenesis**: Object instantiation library
312
313
## Error Handling
314
315
Common error scenarios and solutions:
316
317
**Missing PowerMock ObjectFactory:**
318
```
319
IllegalStateException: Missing org.powermock.modules.testng.PowerMockObjectFactory in classpath
320
```
321
Solution: Ensure powermock-module-testng is in test classpath
322
323
**Runtime Creation Errors:**
324
```
325
RuntimeException: Cannot create a new instance of test class
326
```
327
Solution: Check that test class has accessible constructor and PowerMock annotations are correct
328
329
**ClassLoader Issues:**
330
Tests may fail if PowerMock classloader conflicts with other bytecode manipulation. Use method-level `@PrepareForTest` to minimize scope when needed.