NUnit Test a method including Request.Cookies
If you want to run Nunit testing on some ASP.NET code, then you might have some problems if the code being tested
makes reference to Request.Cookies. Here is how I got round it:
/// <summary>
/// Verify that critical parts of the default page are working
/// </summary>
[TestFixture]
public class DefaultMasterTesting
{
/// <summary>
/// Checks the Some Request.Cookies dependentent method
/// </summary>
[Test]
public void CheckSomeCookieDependentMethod()
{
var master = new Default();
master.Page = new Page();
var hrReq = new HttpRequest(“”, “http://localhost”, “”);
hrReq.Cookies.Add(new HttpCookie(“Cookie”, “Cookie Value”));
var hrResp = new HttpResponse(new StringWriter());
HttpContext.Current = new HttpContext(hrReq,hrResp);
var fiRequest = typeof (Page).GetField(“_request”, BindingFlags.NonPublic | BindingFlags.Instance);
fiRequest.SetValue(master.Page,HttpContext.Current.Request);
master.SomeCookieDependentMethod();
}
}
Interesting to see that Page.Request and HttpContext.Current.Request are different !