Den*_*din 8 java junit mockito
我正在尝试模拟在另一个正在进行单元测试的方法中调用的方法。但是,模拟无法正常工作,UnknownHostException如果我从不首先模拟内部方法,我就会得到一个。这可能是我的 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);
}
Run Code Online (Sandbox Code Playgroud)
我正在测试的方法是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();
}
Run Code Online (Sandbox Code Playgroud)
考虑模拟该类并安排在存根所需成员的同时实际调用被测方法。
例如
@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);
}
Run Code Online (Sandbox Code Playgroud)
然而,根据文档,其中之一 Important gotcha on spying real objects!
有时它是不可能或不切实际的
when(Object)用于 stubing 间谍。因此,在使用 spies 时,请考虑使用doReturn|Answer|Throw()系列方法进行 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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3130 次 |
| 最近记录: |