简体   繁体   English

HttpURLConnection总是以模拟方式返回200

[英]HttpURLConnection returns 200 always in mockito

I'm running a test with a HttpURLConnection . 我正在使用HttpURLConnection进行测试。 But I wanted to return 204 as the response code. 但是我想返回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();
}

Implementation 履行

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

Why it returns 200 response code always. 为什么总是返回200响应码。 Are there any workaround to get 204 returned? 是否有任何解决方法来返回204?

whenever we mock method local instantiation using whenNew, we have to add the classname of the method which is instantiating in prepareForTest. 每当我们使用whenNew模拟方法本地实例化时,我们都必须添加在prepareForTest中实例化的方法的类名。

If the className of the method call is MyTask then add it in prepareForTest as below. 如果方法调用的className是MyTask,则将其添加到prepareForTest中,如下所示。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM