HttpURLConnection总是以模拟方式返回200

时间:2019-05-14 03:06:06

标签: java junit powermockito

我正在使用HttpURLConnection进行测试。但是我想返回204作为响应代码。

@Test
public void should_return_result_with_success_data() throws Exception {
    HttpURLConnection urlConnection = PowerMockito.mock(HttpURLConnection.class);
    URL finalUrl = PowerMockito.mock(URL.class);

    PowerMockito.whenNew(URL.class).withArguments("http://sample.com").thenReturn(finalUrl);
    PowerMockito.when(finalUrl.openConnection()).thenReturn(urlConnection);
    PowerMockito.when(urlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_NO_CONTENT);

    task.call();
}

实施

@Override
public EventResult call() throws Exception {
    url = url.concat(URLEncoder.encode(data, StandardCharsets.UTF_8.name()));

    HttpURLConnection connection = (HttpURLConnection) new URL("http://sample.com").openConnection();
    connection.setConnectTimeout(connectionTimeout);
    connection.setReadTimeout(readTimeout);

    EventResult eventResult = new EventResult();
    eventResult.setHttpStatusCode(connection.getResponseCode());

    if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
        return eventResult;
    } else {
        eventResult = JsonPojoConverter.getEventResult(IOUtils.toString(connection.getErrorStream(), StandardCharsets.UTF_8.name()));
    }
    return eventResult;
}

为什么总是返回200响应码。是否有任何解决方法可以返回204?

1 个答案:

答案 0 :(得分:1)

每当我们使用whenNew模拟方法本地实例化时,都必须添加在prepareForTest中实例化的方法的类名。

如果方法调用的className是MyTask,则将其添加到prepareForTest中,如下所示。

@RunWith(PowerMockRunner.class)
@PrepareForTest({MyTask.class})
public class MyTaskTest {

}