Search code examples
c#tdddependency-injectionmocking

How do I inject a WebRequest/Response dependency?


I'm struggling to separate the dependencies in the following code:

    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);

    }

Essentially I want to unit test without relying on the request to the external website.

What would be the best way of going about this?


Solution

  • Not sure how that class looks off of the top of my head, but you can always wrap them around your own, testable class.

    public class WebRequestWrapper
    {
       internal WebRequestWrapper() {..}
    
       public WebRequestWrapper(WebRequest req)
       {
          _innerRequest = req;
       }
    
    
       public virtual string Url
       {
          return _innerReq.Url;
       }
    
       //repeat, make all necessary members virtual
    }
    

    then you can use RhinoMocks to create a PartialMock of this class. IT will override any of the virtual properties.