2016-12-30 119 views
1

我有以下代碼,我希望使用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)'呼叫作爲在建立?

+0

你是對的,它正在執行真正的網絡東西。這是嘲笑客戶和獲取請求後預期嗎?不應該只是返回一個HttpResponse類型的對象而不進行實際的網絡調用? –

+0

有沒有辦法激活這些模擬?我的困惑是如何激活嘲笑當代碼yries初始化這些對象 –

+0

謝謝,那是快速反饋,然後;距離今天的每日上限更近一步;-) – GhostCat

回答

0

你有這麼遠的是:

mockHttpClient = Mockito.mock(HttpClient.class); 
Mockito.when(mockHttpClient.execute(Mockito.isA(HttpGet.class))).thenReturn(mockHttpResponse) 

因此,有一個模擬應該將呼叫反應​​。

然後你有:

1) underTest = new UnderTest(initialize with fake API (api)); 
2) // Trigger method to test 

的問題是:什麼是要麼不對您的1號線或用安裝線2。但是我們不能告訴你;因爲您沒有向我們提供該代碼。

的事情是:爲了您的模擬對象是使用的,它需要通過underTest莫名其妙使用。所以當你在做init的時候會出錯,那麼underTest就不會使用嘲弄的東西,而是一些「真實」的東西。

+0

謝謝,現在有道理。 –