gpt4 book ai didi

java - 在非模拟方法中模拟方法

转载 作者:行者123 更新时间:2023-12-03 11:18:04 25 4
gpt4 key购买 nike

我正在尝试模拟在另一个正在进行单元测试的方法中调用的方法。
但是,模拟无法正常工作,我收到了 UnknownHostException如果我从不首先 mock 内部方法,我就会得到。这可能是我的 throws 声明,因为我不知道该怎么做。任何帮助表示赞赏。

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

@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 ,我想 mock 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();
}

最佳答案

考虑模拟该类并安排在 stub 所需成员的同时实际调用被测方法。

例如

@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!

Sometimes it's impossible or impractical to use when(Object) for stubbing spies. Therefore when using spies please consider doReturn|Answer|Throw() family of methods for stubbing.


@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);
}

关于java - 在非模拟方法中模拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51777649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com