2008-10-28 177 views
0

我掙扎的依賴性在下面的代碼分離:如何注入WebRequest/Response依賴項?

public static SiteConnector ConnectToSite(String Logon, String Password) 
    { 

     HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(_URI); 
     ConfigureRequest(Logon, Password, webRequest); 
     HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); 
     Cookie ReposonseCookie; 
     //this looks for a cookie and spitsout a value based on response 
     int value = ProcessResponse(webResponse,out ReposonseCookie); 

     return new SiteConnector(ReposonseCookie, value); 

    } 

基本上我想單元測試不依賴於請求到外部網站。

要做這件事的最好方法是什麼?

回答

2

不知道這個班怎麼看不起我的頭頂,但你總是可以把它們包裝在你自己的可測試班上。

public class WebRequestWrapper 
{ 
    internal WebRequestWrapper() {..} 

    public WebRequestWrapper(WebRequest req) 
    { 
     _innerRequest = req; 
    } 


    public virtual string Url 
    { 
     return _innerReq.Url; 
    } 

    //repeat, make all necessary members virtual 
} 

然後您可以使用RhinoMocks創建此類的PartialMock。 IT將覆蓋任何虛擬屬性。