<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Richard Willis &#187; Unit Testing</title>
	<atom:link href="http://blog.salamandersoft.co.uk/index.php/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.salamandersoft.co.uk</link>
	<description>SalamanderSoft, SharePoint Learning Kit, Microsoft Learning Gateway &#38; SharePoint Development</description>
	<lastBuildDate>Thu, 29 Jul 2010 00:13:51 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>How to Mock HttpWebRequest when Unit Testing</title>
		<link>http://blog.salamandersoft.co.uk/index.php/2009/10/how-to-mock-httpwebrequest-when-unit-testing/</link>
		<comments>http://blog.salamandersoft.co.uk/index.php/2009/10/how-to-mock-httpwebrequest-when-unit-testing/#comments</comments>
		<pubDate>Sun, 18 Oct 2009 21:34:23 +0000</pubDate>
		<dc:creator>Richard</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog.salamandersoft.co.uk/index.php/2009/10/how-to-mock-httpwebrequest-when-unit-testing/</guid>
		<description><![CDATA[One of our latest products interacts with a Restful web service. As this is the core part of its functionality as part of Test Driven Development and Unit Testing I needed to be able to test the calls to the web service using HttpWebRequest.
A quick Google didn&#8217;t come up with anything so I started looking [...]]]></description>
			<content:encoded><![CDATA[<p>One of our latest products interacts with a Restful web service. As this is the core part of its functionality as part of Test Driven Development and Unit Testing I needed to be able to test the calls to the web service using HttpWebRequest.</p>
<p>A quick Google didn&#8217;t come up with anything so I started looking at the best way to mock the calls. My initial thought was to extract all use of HttpWebRequest into a separate class, define an interface for setting the request and getting the response and use <a href="http://martinfowler.com/articles/injection.html">Dependency Injection</a> to determine whether to use the &#8216;normal&#8217; class or a mock.</p>
<p>Then I looked a bit closer at WebRequest.Create which is the method you use to create a HttpWebRequest. I noticed that it uses a <a href="http://en.wikipedia.org/wiki/Factory_method_pattern">Factory Method</a> so you could actually register your own factory object depending on the url used. So without any extra code required in the class under test, you can register your factory object and the .Net Framework will automatically use your mocks or stubs. This is pretty cool.</p>
<p>To take advantage of this you need to implement the <a href="http://msdn.microsoft.com/en-us/library/system.net.iwebrequestcreate.aspx">IWebRequestCreate interface</a> on your factory object, and then register your factory object with <a href="http://msdn.microsoft.com/en-us/library/system.net.iwebrequestcreate.aspx">WebRequest.RegisterPrefix</a>. What you do in the Create method is up to you, but I created a simple WebRequest and WebResponse pair which store the request for you to test the input, and which returns a configurable response.</p>
<p>First an example of how you can use these:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:92161342-cacd-4673-be5c-c39bad37d2dc" class="wlWriterEditableSmartContent">
<pre style="background-color:#FFFFFF;overflow: none;"><span style="color: #0000FF;">string</span><span style="color: #000000;"> response </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #800000;">"</span><span style="color: #800000;">my response string here</span><span style="color: #800000;">"</span><span style="color: #000000;">;
WebRequest.RegisterPrefix(</span><span style="color: #800000;">"</span><span style="color: #800000;">test</span><span style="color: #800000;">"</span><span style="color: #000000;">, </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> TestWebRequestCreate());
TestWebRequest request </span><span style="color: #000000;">=</span><span style="color: #000000;"> TestWebRequestCreate.CreateTestRequest(response);

</span><span style="color: #0000FF;">string</span><span style="color: #000000;"> url </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #800000;">"</span><span style="color: #800000;">test://MyUrl</span><span style="color: #800000;">"</span><span style="color: #000000;">;

ObjectUnderTest myObject </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> ObjectUnderTest();
myObject.Url </span><span style="color: #000000;">=</span><span style="color: #000000;"> url;
</span><span style="color: #008000;">//</span><span style="color: #008000;"> DoStuff call the url with a request and then processes the
</span><span style="color: #008000;">//</span><span style="color: #008000;"> response as set above</span><span style="color: #008000;">
</span><span style="color: #000000;">myObject.DoStuff();

</span><span style="color: #0000FF;">string</span><span style="color: #000000;"> requestContent </span><span style="color: #000000;">=</span><span style="color: #000000;"> request.ContentAsString();
Assert.AreEqual(expectedRequestContent, requestContent);
</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
<p>The code for these 3 objects is:</p>
</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:db2b1ee8-5c07-4199-a0f9-92982406f330" class="wlWriterEditableSmartContent">
<pre style="background-color:#FFFFFF;overflow: none;"><span style="color: #808080;">///</span><span style="color: #008000;"> </span><span style="color: #808080;">&lt;summary&gt;</span><span style="color: #008000;">A web request creator for unit testing.</span><span style="color: #808080;">&lt;/summary&gt;</span><span style="color: #808080;">
</span><span style="color: #0000FF;">class</span><span style="color: #000000;"> TestWebRequestCreate : IWebRequestCreate
{
    </span><span style="color: #0000FF;">static</span><span style="color: #000000;"> WebRequest nextRequest;
    </span><span style="color: #0000FF;">static</span><span style="color: #000000;"> </span><span style="color: #0000FF;">object</span><span style="color: #000000;"> lockObject </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> </span><span style="color: #0000FF;">object</span><span style="color: #000000;">();

    </span><span style="color: #0000FF;">static</span><span style="color: #000000;"> </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> WebRequest NextRequest
    {
        </span><span style="color: #0000FF;">get</span><span style="color: #000000;"> { </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> nextRequest ;}
        </span><span style="color: #0000FF;">set</span><span style="color: #000000;">
        {
            </span><span style="color: #0000FF;">lock</span><span style="color: #000000;"> (lockObject)
            {
                nextRequest </span><span style="color: #000000;">=</span><span style="color: #000000;"> value;
            }
        }
    }

    </span><span style="color: #808080;">///</span><span style="color: #008000;"> </span><span style="color: #808080;">&lt;summary&gt;</span><span style="color: #008000;">See </span><span style="color: #808080;">&lt;see cref="IWebRequestCreate.Create"/&gt;</span><span style="color: #008000;">.</span><span style="color: #808080;">&lt;/summary&gt;</span><span style="color: #808080;">
</span><span style="color: #000000;">    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> WebRequest Create(Uri uri)
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> nextRequest;
    }

    </span><span style="color: #808080;">///</span><span style="color: #008000;"> </span><span style="color: #808080;">&lt;summary&gt;</span><span style="color: #008000;">Utility method for creating a TestWebRequest and setting
    </span><span style="color: #808080;">///</span><span style="color: #008000;"> it to be the next WebRequest to use.</span><span style="color: #808080;">&lt;/summary&gt;</span><span style="color: #008000;">
    </span><span style="color: #808080;">///</span><span style="color: #008000;"> </span><span style="color: #808080;">&lt;param name="response"&gt;</span><span style="color: #008000;">The response the TestWebRequest will return.</span><span style="color: #808080;">&lt;/param&gt;</span><span style="color: #808080;">
</span><span style="color: #000000;">    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">static</span><span style="color: #000000;"> TestWebRequest CreateTestRequest(</span><span style="color: #0000FF;">string</span><span style="color: #000000;"> response)
    {
        TestWebRequest request </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> TestWebRequest(response);
        NextRequest </span><span style="color: #000000;">=</span><span style="color: #000000;"> request;
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> request;
    }
}

</span><span style="color: #0000FF;">class</span><span style="color: #000000;"> TestWebRequest : WebRequest
{
    MemoryStream requestStream </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> MemoryStream();
    MemoryStream responseStream;

    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">override</span><span style="color: #000000;"> </span><span style="color: #0000FF;">string</span><span style="color: #000000;"> Method { </span><span style="color: #0000FF;">get</span><span style="color: #000000;">; </span><span style="color: #0000FF;">set</span><span style="color: #000000;">; }
    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">override</span><span style="color: #000000;"> </span><span style="color: #0000FF;">string</span><span style="color: #000000;"> ContentType { </span><span style="color: #0000FF;">get</span><span style="color: #000000;">; </span><span style="color: #0000FF;">set</span><span style="color: #000000;">; }
    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">override</span><span style="color: #000000;"> </span><span style="color: #0000FF;">long</span><span style="color: #000000;"> ContentLength { </span><span style="color: #0000FF;">get</span><span style="color: #000000;">; </span><span style="color: #0000FF;">set</span><span style="color: #000000;">; }

    </span><span style="color: #808080;">///</span><span style="color: #008000;"> </span><span style="color: #808080;">&lt;summary&gt;</span><span style="color: #008000;">Initializes a new instance of </span><span style="color: #808080;">&lt;see cref="TestWebRequest"/&gt;</span><span style="color: #008000;">
    </span><span style="color: #808080;">///</span><span style="color: #008000;"> with the response to return.</span><span style="color: #808080;">&lt;/summary&gt;</span><span style="color: #808080;">
</span><span style="color: #000000;">    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> TestWebRequest(</span><span style="color: #0000FF;">string</span><span style="color: #000000;"> response)
    {
        responseStream </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> MemoryStream(System.Text.Encoding.UTF8.GetBytes(response));
    }

    </span><span style="color: #808080;">///</span><span style="color: #008000;"> </span><span style="color: #808080;">&lt;summary&gt;</span><span style="color: #008000;">Returns the request contents as a string.</span><span style="color: #808080;">&lt;/summary&gt;</span><span style="color: #808080;">
</span><span style="color: #000000;">    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">string</span><span style="color: #000000;"> ContentAsString()
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> System.Text.Encoding.UTF8.GetString(requestStream.ToArray());
    }

    </span><span style="color: #808080;">///</span><span style="color: #008000;"> </span><span style="color: #808080;">&lt;summary&gt;</span><span style="color: #008000;">See </span><span style="color: #808080;">&lt;see cref="WebRequest.GetRequestStream"/&gt;</span><span style="color: #008000;">.</span><span style="color: #808080;">&lt;/summary&gt;</span><span style="color: #808080;">
</span><span style="color: #000000;">    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">override</span><span style="color: #000000;"> Stream GetRequestStream()
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> requestStream;
    }

    </span><span style="color: #808080;">///</span><span style="color: #008000;"> </span><span style="color: #808080;">&lt;summary&gt;</span><span style="color: #008000;">See </span><span style="color: #808080;">&lt;see cref="WebRequest.GetResponse"/&gt;</span><span style="color: #008000;">.</span><span style="color: #808080;">&lt;/summary&gt;</span><span style="color: #808080;">
</span><span style="color: #000000;">    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">override</span><span style="color: #000000;"> WebResponse GetResponse()
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> </span><span style="color: #0000FF;">new</span><span style="color: #000000;"> TestWebReponse(responseStream);
    }
}

</span><span style="color: #0000FF;">class</span><span style="color: #000000;"> TestWebReponse : WebResponse
{
    Stream responseStream;

    </span><span style="color: #808080;">///</span><span style="color: #008000;"> </span><span style="color: #808080;">&lt;summary&gt;</span><span style="color: #008000;">Initializes a new instance of </span><span style="color: #808080;">&lt;see cref="TestWebReponse"/&gt;</span><span style="color: #008000;">
    </span><span style="color: #808080;">///</span><span style="color: #008000;"> with the response stream to return.</span><span style="color: #808080;">&lt;/summary&gt;</span><span style="color: #808080;">
</span><span style="color: #000000;">    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> TestWebReponse(Stream responseStream)
    {
        </span><span style="color: #0000FF;">this</span><span style="color: #000000;">.responseStream </span><span style="color: #000000;">=</span><span style="color: #000000;"> responseStream;
    }

    </span><span style="color: #808080;">///</span><span style="color: #008000;"> </span><span style="color: #808080;">&lt;summary&gt;</span><span style="color: #008000;">See </span><span style="color: #808080;">&lt;see cref="WebResponse.GetResponseStream"/&gt;</span><span style="color: #008000;">.</span><span style="color: #808080;">&lt;/summary&gt;</span><span style="color: #808080;">
</span><span style="color: #000000;">    </span><span style="color: #0000FF;">public</span><span style="color: #000000;"> </span><span style="color: #0000FF;">override</span><span style="color: #000000;"> Stream GetResponseStream()
    {
        </span><span style="color: #0000FF;">return</span><span style="color: #000000;"> responseStream;
    }
}
</span></pre>
<p><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin.  http://dunnhq.com --></div>
</p>
<p>This is quite a simple implementation, just to check the request and return a known response. Once you&#8217;ve got this working, you can obviously do more tests such as simulating error conditions.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.salamandersoft.co.uk/index.php/2009/10/how-to-mock-httpwebrequest-when-unit-testing/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
