[英]Issues with Mocking HttpURLConnection using Mockito
我正在嘗試模擬HttpURLConnection對象,但似乎無法正確處理。 這是我要測試的方法。
@Override
public JSON connect() throws IOException {
HttpURLConnection httpConnection;
String finalUrl = url;
URL urlObject = null;
int status = 0;
//recursively check for redirected uri if the given uri is moved
do{
urlObject = getURL(finalUrl);
httpConnection = (HttpURLConnection) urlObject.openConnection();
//httpConnection.setInstanceFollowRedirects(true);
//httpConnection.connect();
status = httpConnection.getResponseCode();
if (300 > status && 400 < status){
continue;
}
String redirectedUrl = httpConnection.getHeaderField("Location");
if(null == redirectedUrl){
break;
}
finalUrl =redirectedUrl;
}while (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK);
return JSONSerializer.toJSON(getData(httpConnection).toString());
}
這是我所做的。
@Before
public void setUp() throws Exception{
//httpConnectGithubHandle = new HttpConnectGithub(VALID_URL);
httpConnectGithubHandle = mock(HttpConnectGithub.class);
testURL = new URL(VALID_URL);
mockHttpURLConnection = mock(HttpURLConnection.class);
mockInputStreamReader = mock(InputStreamReader.class);
mockBufferedReader = mock(BufferedReader.class);
mockInputStream = mock(InputStream.class);
when(httpConnectGithubHandle.getData(mockHttpURLConnection)).thenReturn(SOME_STRING);
when(httpConnectGithubHandle.getURL(SOME_STRING)).thenReturn(testURL);
when(mockHttpURLConnection.getResponseCode()).thenReturn(200);
when(mockHttpURLConnection.getHeaderField(LOCATION)).thenReturn(SOME_STRING);
PowerMockito.whenNew(InputStreamReader.class)
.withArguments(mockInputStream).thenReturn(mockInputStreamReader);
PowerMockito.whenNew(BufferedReader.class)
.withArguments(mockInputStreamReader).thenReturn(mockBufferedReader);
PowerMockito.when(mockBufferedReader.readLine())
.thenReturn(JSON_STRING)
.thenReturn(null);
}
那就是我的setUp方法。 此方法調用的方法的測試用例成功。 我的實際測試用例如下。
@Test
public void testConnect() throws IOException {
JSON jsonObject = httpConnectGithubHandle.connect();
System.out.println(jsonObject);
assertThat(jsonObject, instanceOf(JSON.class));
}
我試圖打印數據,它顯示為空。
目前,您僅在測試模擬。 在模擬上調用httpConnectGithubHandle.connect()
,並且模擬未返回任何行為,因此模擬返回null。 您應該在測試中使用真實的HttpConnectGithub
對象。 (取消注釋測試的第一行,並刪除HttpConnectGithub
模擬。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.