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

왜 t는 'client.execute(get)' 전화를 조롱하지 않습니다 설정?

+0

당신은 진짜 네트워크 물건을 실행하고 있다는 것입니다. 클라이언트와 get 요청을 조롱 한 후 이것이 예상됩니까? 실제 네트워크 호출을하지 않고 HttpResponse 유형의 객체 만 반환하면 안됩니까? –

+0

이러한 모의 광고를 활성화 할 수있는 방법이 있습니까? 내 혼란은 코드가 이러한 객체를 초기화하려고 할 때 mock을 활성화하는 방법입니다. –

+0

감사합니다. 오늘 일일 한도에 한 걸음 더 다가 가겠다. ;-) – GhostCat

답변

0

은 당신이 지금까지 가지고 것은 :

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

그래서 execute()의 호출에 반응해야 모의있다.

그리고는, 당신은 :

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

문제는 : 뭔가 당신의 라인 1 또는 설치 라인 2 문제 중 하나입니다. 그러나 우리는 당신을 말할 수 없다; 당신이 우리에게 그 코드를 제공하지 않기 때문입니다.

것은이 : 당신의 모의 객체가 사용되기를 위해서는, 그것은 어떻게 든 underTest에 의해을 사용해야합니다. 그래서 당신이 init stuff을 어떻게 든 잘못하고 있다면, underTest는 조롱 된 것을 사용하지 않고 "진짜"일을 사용합니다.

+0

고마워, 그건 이제 의미가있다. –

관련 문제