我正在使用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?

最佳答案

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

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

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

}

09-26 19:34