使用mockito模拟HttpClient请求

use*_*mda 2 junit unit-testing httpclient mockito unknown-host

我希望使用 Junit 和 Mockito 测试以下代码。

要测试的代码:

    Header header = new BasicHeader(HttpHeaders.AUTHORIZATION,AUTH_PREAMBLE + token);
    List<Header> headers = new ArrayList<Header>();
    headers.add(header);
    HttpClient client = HttpClients.custom().setDefaultHeaders(headers).build();
    HttpGet get = new HttpGet("real REST API here"));
    HttpResponse response = client.execute(get);
    String json_string_response = EntityUtils.toString(response.getEntity());
Run Code Online (Sandbox Code Playgroud)

和测试

protected static HttpClient mockHttpClient;
protected static HttpGet mockHttpGet;
protected static HttpResponse mockHttpResponse;
protected static StatusLine mockStatusLine;
protected static HttpEntity mockHttpEntity;





@BeforeClass
public static void setup() throws ClientProtocolException, IOException {
    mockHttpGet = Mockito.mock(HttpGet.class);
    mockHttpClient = Mockito.mock(HttpClient.class);
    mockHttpResponse = Mockito.mock(HttpResponse.class);
    mockStatusLine = Mockito.mock(StatusLine.class);
    mockHttpEntity = Mockito.mock(HttpEntity.class);

    Mockito.when(mockHttpClient.execute(Mockito.isA(HttpGet.class))).thenReturn(mockHttpResponse);
    Mockito.when(mockHttpResponse.getStatusLine()).thenReturn(mockStatusLine);
    Mockito.when(mockStatusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK);
    Mockito.when(mockHttpResponse.getEntity()).thenReturn(mockHttpEntity);

}


@Test
underTest = new UnderTest(initialize with fake API (api));
//Trigger method to test
Run Code Online (Sandbox Code Playgroud)

这给了我一个错误:

java.net.UnknownHostException:api:提供节点名或服务名,或未知

为什么不按照'client.execute(get)'设置中的方式模拟呼叫?

Gho*_*ica 5

到目前为止你所拥有的是:

mockHttpClient = Mockito.mock(HttpClient.class);
Mockito.when(mockHttpClient.execute(Mockito.isA(HttpGet.class))).thenReturn(mockHttpResponse)
Run Code Online (Sandbox Code Playgroud)

因此,有一个模拟应该对 的调用做出反应execute()

然后你有:

1) underTest = new UnderTest(initialize with fake API (api));
2) // Trigger method to test
Run Code Online (Sandbox Code Playgroud)

问题是:您的设置中的第 1 行或第 2 行有问题。但我们不能告诉你;因为您没有向我们提供该代码。

问题是:为了让你的模拟对象有用,它需要被underTest以某种方式使用。因此,当您以某种方式错误地执行初始化操作时,underTest 不会使用模拟的东西,而是使用一些“真实”的东西。