2016-12-30 125 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

谢谢,现在有道理。 –