简体   繁体   中英

HttpURLConnection returns 200 always in mockito

I'm running a test with a HttpURLConnection . But I wanted to return 204 as the response code.

@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. Are there any workaround to get 204 returned?

whenever we mock method local instantiation using whenNew, we have to add the classname of the method which is instantiating in prepareForTest.

If the className of the method call is MyTask then add it in prepareForTest as below.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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