在非模拟方法中模拟方法

时间:2018-08-10 01:12:55

标签: java junit mockito

我正在尝试模拟正在单元测试的另一个方法内部调用的方法。 但是,该模拟无法正常工作,如果我从不首先模拟内部方法,则会得到UnknownHostException。可能是我抛出的声明,因为我不知道还有其他方法。任何帮助表示赞赏。

到目前为止,我的测试是:

@Test
public void testServiceValidHost() throws ClientProtocolException, IOException {
    HealthService service = new HealthService();
    HealthService spy = Mockito.spy(service);

    when(spy.getHTTPResponse("http://" + HOST + "/health")).thenReturn(SOMESTATUS);

    String actual = spy. executeHealthCheck(HOST);
    assertEquals(SOMESTATUS, actual);
}

我正在测试的方法是executeHealthCheck,我想模拟getHTTPResponse

public String executeHealthCheck(String host) {
    try {
        String responseBody = getHTTPResponse("http://" + host + "/health");
        return responseBody;
    } catch (UnknownHostException e) {
        ...
        return "Invalid Host";
    } catch (Exception e) {
        ...
        return "Error";
    }
}

public String getHTTPResponse(String url) throws IOException, ClientProtocolException {
    CloseableHttpResponse response = null;
    HttpGet httpGet = new HttpGet(url);
    response = client.execute(httpGet);
    JSONObject responseBody = new JSONObject(EntityUtils.toString(response.getEntity()));
    return responseBody.toString();
}

1 个答案:

答案 0 :(得分:2)

考虑对类进行模拟,并安排在存入所需成员时实际调用被测方法。

例如

@Test
public void testServiceValidHost() throws ClientProtocolException, IOException {
    //Arrange    
    HealthService service = Mockito.mock(HealthService.class);

    when(service.executeHealthCheck(HOST)).callRealMethod();
    when(service.getHTTPResponse("http://" + HOST + "/health")).thenReturn(SOMESTATUS);

    //Act
    String actual = service.executeHealthCheck(HOST);

    //Assert
    assertEquals(SOMESTATUS, actual);
}

但是根据文档,Important gotcha on spying real objects!

之一
  

有时使用when(Object)来对间谍进行打桩是不可能或不切实际的。因此,使用间谍程序时,请考虑使用 doReturn | Answer | Throw()系列方法进行存根。

@Test
public void testServiceValidHost() throws ClientProtocolException, IOException {
    //Arrange
    HealthService service = new HealthService();
    HealthService spy = Mockito.spy(service);

    //You have to use doReturn() for stubbing
    doReturn(SOMESTATUS).when(spy).getHTTPResponse("http://" + HOST + "/health");

    //Act
    String actual = spy.executeHealthCheck(HOST);

    //Assert
    assertEquals(SOMESTATUS, actual);
}