我有以下代碼,我希望使用Junit和Mockito進行測試。使用mockito嘲笑HttpClient請求
代碼來測試:
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());
和測試
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
這給了我一個錯誤:
java.net.UnknownHostException: api: nodename nor servname provided, or not known
爲什麼牛逼不是嘲笑'client.execute(get)'
呼叫作爲在建立?
你是對的,它正在執行真正的網絡東西。這是嘲笑客戶和獲取請求後預期嗎?不應該只是返回一個HttpResponse類型的對象而不進行實際的網絡調用? –
有沒有辦法激活這些模擬?我的困惑是如何激活嘲笑當代碼yries初始化這些對象 –
謝謝,那是快速反饋,然後;距離今天的每日上限更近一步;-) – GhostCat