【发布时间】:2016-08-06 14:23:20
【问题描述】:
我写了一个简单的方法,它应该接受一个 url 并通过一个 get 请求从这个 url 检索数据。该方法如下所示:
public String getResponse(String connectionUrl) throws HttpException {
HttpURLConnection connection = null;
try {
URL url = new URL(connectionUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
throw new HttpException("Response code was " + responseCode + " (should be 200)");
}
Scanner scanner = new Scanner(connection.getInputStream()).useDelimiter("\\A");
String response = scanner.hasNext() ? scanner.next() : "";
connection.disconnect();
scanner.close();
return response;
} catch (IOException e) {
if (connection != null) {
connection.disconnect();
}
throw new HttpException(e.getMessage(), e.getCause());
}
}
现在我正在为此方法编写单元测试。我使用 PowerMock 和 Mockito 和 JUnit 来编写我的测试。有问题的测试如下所示:
@Test
public void getResponse_NormalResponse() throws Exception {
String expectedResponse = "This is the expected response text!";
URL url = PowerMockito.mock(URL.class);
HttpURLConnection connection = PowerMockito.mock(HttpURLConnection.class);
InputStream inputStream = PowerMockito.mock(InputStream.class);
Scanner scanner = PowerMockito.mock(Scanner.class);
PowerMockito.whenNew(URL.class).withArguments(REQUEST_URL).thenReturn(url);
PowerMockito.whenNew(Scanner.class).withArguments(inputStream).thenReturn(scanner);
PowerMockito.when(url.openConnection()).thenReturn(connection);
// Response code mocked here
PowerMockito.when(connection.getResponseCode()).thenReturn(200);
PowerMockito.when(connection.getInputStream()).thenReturn(inputStream);
PowerMockito.when(scanner.hasNext()).thenReturn(true);
PowerMockito.when(scanner.next()).thenReturn(expectedResponse);
HttpClient httpClient = new HttpClient();
String actualResponse = httpClient.getResponse(REQUEST_URL);
Assert.assertEquals("Response is wrong!", expectedResponse, actualResponse);
}
但是当我运行测试时,会抛出 HttpException,因为响应代码是 404。测试是使用 PowerMockRunner 运行的。我做错了什么,为什么这个测试不能正常工作?
【问题讨论】:
-
我建议重构方法代码,这样您就可以在没有 PowerMock 的情况下对其进行测试,不需要进行太多更改。
-
你建议改变什么?
-
提示:另一个更理智的想法,而不是使用 PowerMock 是简单地不在你的方法中进行新的调用。你看,如果你创建了难以测试的代码;那么当它很难测试时不要感到惊讶。见youtube.com/playlist?list=PLD0011D00849E1B79
标签: java junit mocking mockito powermock