0
# Static Method Mocking
1
2
PowerMock enables mocking of static methods, allowing you to control the behavior of static calls in your tests. This is essential for testing code that depends on static utilities, system calls, or third-party static APIs without requiring major refactoring.
3
4
## Capabilities
5
6
### Basic Static Mocking
7
8
Enable static mocking for one or more classes, making all static methods on those classes mockable.
9
10
```java { .api }
11
static void mockStatic(Class<?> type, Class<?>... types);
12
```
13
14
**Parameters:**
15
- `type` - The primary class to enable static mocking for
16
- `types` - Additional classes to enable static mocking for (optional)
17
18
**Usage Example:**
19
```java
20
@Test
21
@PrepareForTest({FileUtils.class, StringUtils.class})
22
public void testMultipleStaticMocks() {
23
mockStatic(FileUtils.class, StringUtils.class);
24
25
when(FileUtils.readFileToString(any(File.class))).thenReturn("file content");
26
when(StringUtils.isEmpty(anyString())).thenReturn(false);
27
28
// Test code that uses both static methods
29
String result = MyService.processFile(new File("test.txt"));
30
assertEquals("processed: file content", result);
31
}
32
```
33
34
### Static Mocking with Custom Answer
35
36
Create static mocks with a custom default answer strategy for unstubbed method calls.
37
38
```java { .api }
39
static void mockStatic(Class<?> classMock, Answer defaultAnswer);
40
```
41
42
**Parameters:**
43
- `classMock` - The class to enable static mocking for
44
- `defaultAnswer` - Default answer strategy for unstubbed methods
45
46
**Usage Example:**
47
```java
48
@Test
49
@PrepareForTest(SystemUtils.class)
50
public void testStaticMockWithCustomAnswer() {
51
mockStatic(SystemUtils.class, RETURNS_SMART_NULLS);
52
53
// Only stub specific method, others return smart nulls
54
when(SystemUtils.getJavaVersion()).thenReturn("1.8.0");
55
56
String version = SystemUtils.getJavaVersion(); // Returns "1.8.0"
57
String os = SystemUtils.getOSName(); // Returns smart null
58
}
59
```
60
61
### Static Mocking with Settings
62
63
Create static mocks with advanced MockSettings configuration for specialized testing scenarios.
64
65
```java { .api }
66
static void mockStatic(Class<?> classToMock, MockSettings mockSettings);
67
```
68
69
**Parameters:**
70
- `classToMock` - The class to enable static mocking for
71
- `mockSettings` - Advanced mock configuration settings
72
73
**Usage Example:**
74
```java
75
@Test
76
@PrepareForTest(DatabaseUtils.class)
77
public void testStaticMockWithSettings() {
78
mockStatic(DatabaseUtils.class,
79
withSettings()
80
.name("DatabaseUtilsMock")
81
.defaultAnswer(RETURNS_DEEP_STUBS));
82
83
when(DatabaseUtils.getConnection().createStatement().executeQuery(anyString()))
84
.thenReturn(mockResultSet);
85
86
ResultSet result = DatabaseUtils.getConnection()
87
.createStatement()
88
.executeQuery("SELECT * FROM users");
89
assertEquals(mockResultSet, result);
90
}
91
```
92
93
## Common Patterns
94
95
### Testing System Dependencies
96
97
```java
98
@Test
99
@PrepareForTest(System.class)
100
public void testSystemDependency() {
101
mockStatic(System.class);
102
when(System.currentTimeMillis()).thenReturn(1234567890L);
103
104
TimestampService service = new TimestampService();
105
long timestamp = service.getCurrentTimestamp();
106
107
assertEquals(1234567890L, timestamp);
108
}
109
```
110
111
### Mocking Third-Party Static APIs
112
113
```java
114
@Test
115
@PrepareForTest(HttpClients.class)
116
public void testHttpClientUsage() {
117
mockStatic(HttpClients.class);
118
CloseableHttpClient mockClient = mock(CloseableHttpClient.class);
119
when(HttpClients.createDefault()).thenReturn(mockClient);
120
121
MyHttpService service = new MyHttpService();
122
service.makeRequest("http://example.com");
123
124
verify(mockClient).execute(any(HttpGet.class));
125
}
126
```
127
128
### Partial Static Mocking
129
130
```java
131
@Test
132
@PrepareForTest(MathUtils.class)
133
public void testPartialStaticMocking() {
134
mockStatic(MathUtils.class);
135
136
// Stub only specific methods, let others use real implementation
137
when(MathUtils.complexCalculation(anyDouble())).thenReturn(42.0);
138
doCallRealMethod().when(MathUtils.class);
139
MathUtils.simpleAddition(2, 3); // This will call real method
140
141
double result = MathUtils.complexCalculation(100.0); // Returns 42.0
142
assertEquals(42.0, result, 0.001);
143
}
144
```
145
146
## Requirements
147
148
- Classes must be specified in `@PrepareForTest` annotation
149
- Test must use `@RunWith(PowerMockRunner.class)` or equivalent
150
- Static mocking must be enabled before any stubbing
151
- All static method calls on mocked classes go through PowerMock's interception