Mock Static Methods with Mockito
Published
Utilizing PowerMockito with Mockito Prior to v3.4.0
pom.xml
<properties>
<powermock.version>2.0.2</powermock.version>
</properties>
<dependencies>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
HttpClient
, commonly used for invoking external APIs, as an example to write unit test using PowerMockito.RestClientServieimpl.java
public HttpClient getHttpClient(int... timeout) {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
int connectionTimeout = Arrays.stream(timeout).findFirst()
.orElse(CONNECTION_TIMEOUT);
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(connectionTimeout * 1000)
.setConnectionRequestTimeout(connectionTimeout * 1000)
.setSocketTimeout(connectionTimeout * 1000).build();
httpClientBuilder.setDefaultRequestConfig(config);
return httpClientBuilder.build();
}
RestClientServieimplTest.java
public class RestClientServieimplTest {
CloseableHttpClient httpClient;
HttpClientBuilder httpClientBuilder;
RestClientServieImpl restClient;
public void setup() {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(HttpClientBuilder.class);
Mockito.when(HttpClientBuilder.create()).thenReturn(httpClientBuilder);
Mockito.when(httpClientBuilder.build()).thenReturn(httpClient);
}
public void getHttpClientTest() {
Assert.assertNotNull(restClient);
HttpClient httpClient = restClient.getHttpClient();
Assert.assertNotNull(httpClient);
}
}