다음 코드는 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)'
전화를 조롱하지 않습니다 설정?
당신은 진짜 네트워크 물건을 실행하고 있다는 것입니다. 클라이언트와 get 요청을 조롱 한 후 이것이 예상됩니까? 실제 네트워크 호출을하지 않고 HttpResponse 유형의 객체 만 반환하면 안됩니까? –
이러한 모의 광고를 활성화 할 수있는 방법이 있습니까? 내 혼란은 코드가 이러한 객체를 초기화하려고 할 때 mock을 활성화하는 방법입니다. –
감사합니다. 오늘 일일 한도에 한 걸음 더 다가 가겠다. ;-) – GhostCat