2013-10-25 119 views
1

我試圖嘲笑一個HttpURLConnection對象,但我似乎無法正確理解。 這裏是我想測試的方法。使用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)); 
    } 

我試圖打印數據,它顯示爲空。

回答

2

目前your're只測試模擬。在模擬上調用httpConnectGithubHandle.connect(),並且模擬返回null,因爲沒有定義行爲。你應該在你的測試中使用一個真實的HttpConnectGithub對象。 (取消註釋測試的第一行並刪除HttpConnectGithub模擬。)

+0

使用正確的測試用例進行編輯。 getData()返回SOME_STRING。但connect()返回null。那是我的問題。 – BudsNanKis

+0

編輯我的答案。 –

+0

那也是如此,問題在於mockHttpClient。由於某些原因,它無法自動嘲笑它。解決的辦法是通過一些方法將httpclient作爲參數傳遞(在我的情況下是構造函數) – BudsNanKis