2

Junit と Mockito を使用してテストしたい次のコードがあります。

テストするコード:

    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: ノード名もサーブ名も提供されていないか、不明です

'client.execute(get)'セットアップのように呼び出しをモックしないのはなぜですか?

4

1 に答える 1

4

これまでに持っているものは次のとおりです。

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で使用する必要があるということです。したがって、どういうわけか間違った初期化を行っている場合、underTest はモックされたものではなく、「本物の」ものを使用しています。

于 2016-12-30T19:21:45.827 に答える