美文网首页
Java中的一些mock

Java中的一些mock

作者: 听海吹牛逼的声音 | 来源:发表于2018-09-23 11:30 被阅读0次

mockito能应付很多场景,但是mockito不能够mock static的method。但是可以使用PowerMock来搞定这些事情。目前我使用的有:
mock static
mock System相关的函数。
mock http相关的函数

maven 的dependency 如下

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito</artifactId>
            <version>1.7.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>1.7.4</version>
            <scope>test</scope>
        </dependency>

示例代码,删掉了一些信息,主要表达用法。
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<String, String> 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);
        }
    }
}

相关文章

网友评论

      本文标题:Java中的一些mock

      本文链接:https://www.haomeiwen.com/subject/qoifoftx.html