Reputation: 2646
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?
Upvotes: 0
Views: 670
Reputation: 3087
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 {
}
Upvotes: 1