Friday, April 27, 2007

Manually creating an HttpRequest for testing

I'm currently writing unit tests for some code that uses the information found in the Headers property of an HttpRequest object. As such, I want to be able to create my own HttpRequest object with the appropriate headers.

This isn't as easy as I'd like it to be, as presumably the intent for the class is that you're handed an instance of it at the appropriate time, rather than putting one together yourself (which is fair enough).

Time to delve into System.Reflection for a bit of hacking:
// Whip up a fake HttpRequest
HttpRequest httpRequest = new HttpRequest("default.aspx", "http://www.diuturnal.com/default.aspx", string.Empty);
// Have to access the Headers collection first as this creates the internal collection we're about to hack
NameValueCollection headers = httpRequest.Headers;
// Accessing Headers property above will have created the private _headers member, so now we can grab it
headers = (NameValueCollection) httpRequest.GetType().GetField("_headers", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(httpRequest);
PropertyInfo readOnlyInfo = headers.GetType().GetProperty("IsReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
// Hack the collection to not be read-only then add some headers
readOnlyInfo.SetValue(headers, false, null);
headers["Accept"] = "text/xml,application/xml,application/xhtml+xml,text/html;
q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
headers["User-Agent"] = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.2) Gecko/20070219 Firefox/2.0.0.2";
// Finished hacking, set it back to read-only
readOnlyInfo.SetValue(headers, true, null);
view raw HttpRequest.cs hosted with ❤ by GitHub
Job done!