2012-09-06 33 views
1

如何將HttpURLConnection的嘲笑到的getContent()示例代碼的方法,還如何從模擬網址,以獲取效應初探Junit的:如何嘲笑HttpURLConnection的

public class WebClient { 
    public String getContent(URL url) { 
     StringBuffer content = new StringBuffer(); 
     try { 

      HttpURLConnection connection = createHttpURLConnection(url); 
      connection.setDoInput(true); 
      InputStream is = connection.getInputStream(); 
      int count; 
      while (-1 != (count = is.read())) { 
       content.append(new String(Character.toChars(count))); 
      } 
     } catch (IOException e) { 
      return null; 
     } 
     return content.toString(); 
    } 
    protected HttpURLConnection createHttpURLConnection(URL url) throws IOException{ 
     return (HttpURLConnection)url.openConnection(); 

    } 
} 

感謝

回答

0

你會需要爲此使用存根,看看mockito.org這是一個易於使用的框架。這個想法是模仿類的行爲,並驗證您的代碼是否處理正面和負面的情況。

2

您的Webclient是有點嚴重的測試設計。你應該避免隱藏的依賴關係(基本上大多數new操作)。爲了可嘲弄,這些依賴性應該(最好)被賦予給被測試對象,在它的構造函數或被測試對象中應該保存在一個字段中,以便它們可以被注入。

或者你可以擴展你的Web客戶端一樣

new Webclient() { 
    @Override 
    HttpURLConnection createHttpURLConnection(URL url) throws IOException{ 
    return getMockOfURLConnection(); 
} 

其中​​從嘲弄框架一樣返回的Mockito的HttpURLConnection的一個模擬。然後你可以教這個模擬來返回你想要的並使用verify來檢查它是否被正確調用。

2

您應該重構您的代碼:使用方法URL.openStream()而不是將其轉換爲HttpURLConnection。代碼將會更簡單,更通用,更易於測試。

public class WebClient { 
    public String getContent(final URL url) { 
     final StringBuffer content = new StringBuffer(); 
     try { 
      final InputStream is = url.openStream(); 
      int count; 
      while (-1 != (count = is.read())) 
       content.append(new String(Character.toChars(count))); 
     } catch (final IOException e) { 
      return null; 
     } 
     return content.toString(); 
    } 
} 

然後,你應該嘲笑URL。這是最後一堂課,所以你不能用Mockito來嘲笑它。它仍然是幾種可能性,按優先順序:

在類路徑是假的資源
  1. 測試和使用WebClientTest.class.getResource("fakeResource")得到一個URL
  2. 提取界面StreamProvider允許從URL獲得InputStream注入WebClient
  3. 使用PowerMock嘲笑final class URL