mockito能应付很多场景,但是mockito不能够mock static的method。但是可以使用PowerMock来搞定这些事情。目前我使用的有:
mock static
mock System相关的函数。
mock http相关的函数
maven 的dependency 如下
org.powermock
powermock-api-mockito
1.7.4
test
org.powermock
powermock-module-junit4
1.7.4
test
示例代码,删掉了一些信息,主要表达用法。
mock多个目标类
mock静态方法
any参数
@RunWith(PowerMockRunner.class)
@PrepareForTest({HttpClient.class, HttpClientBuilder.class}) //mock的目标类
public class HttpClientTest {
@Test
public void getEnvironment() {
assertEquals(null, HttpClient.getPortOfCTFBinary());
final Map env = new HashMap<>();
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.getenv()).thenReturn(env);
}
@Test
public void getRequest() {
try {
String url = "test";
HttpClientBuilder mockClientBuilder = PowerMockito.mock(HttpClientBuilder.class);
CloseableHttpClient mockHttpClient = PowerMockito.mock(CloseableHttpClient.class);
CloseableHttpResponse mockResponse = PowerMockito.mock(CloseableHttpResponse.class);
StatusLine mockStatusLine = PowerMockito.mock(StatusLine.class);
PowerMockito.mockStatic(HttpClientBuilder.class);
StringEntity res = new StringEntity("testtest");
assertEquals(null, HttpClient.sendGet(url));
PowerMockito.when(HttpClientBuilder.class, "create").thenReturn(mockClientBuilder);
PowerMockito.when(mockClientBuilder.build()).thenReturn(mockHttpClient);
PowerMockito.when(mockHttpClient.execute(any(HttpGet.class))).thenReturn(mockResponse);
PowerMockito.when(mockResponse.getStatusLine()).thenReturn(mockStatusLine);
PowerMockito.when(mockStatusLine.getStatusCode()).thenReturn(200);
PowerMockito.when(mockResponse.getEntity()).thenReturn(res);
assertEquals("testtest", HttpClient.sendGet(url));
PowerMockito.when(mockStatusLine.getStatusCode()).thenReturn(201);
assertEquals(null, HttpClient.sendGet(url));
} catch (Exception e) {
System.out.println(e);
assertTrue(false);
}
}
}