java - HttpURLConnection 在mockito 中始终返回200

标签 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 吗?

最佳答案

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

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

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

}

关于java - HttpURLConnection 在mockito 中始终返回200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56122452/

相关文章:

java - Java 中的邮寄地址?

java - 如何更改 "private static final String filePath"的值以进行单元测试

testing - 在测试之前和之后做一些事情

android - 帐户 : Mockito Test Account

java - 调用 Mockito doNothing 方法时调用真实方法

android - 即使使用 Mockito 在 Android 中通过单元测试,也总是会出现线程错误

Java HashMap 具有重复键的疯狂行为

java - 从 ArrayList<String> 获取随机项

java - JUnit 错误 : Class names, 'org.junit.runner.JUnitCore' ,只有在显式请求注释处理时才被接受

java - Pass by value vs Pass by reference(两者在内存空间分配上的区别)