Add cookie to Request.Cookies collection

dotnet-practitioner picture dotnet-practitioner · Apr 6, 2012 · Viewed 10.9k times · Source

I am trying to create a wrapper class to process content of HttpContext. I am creating a cookie but unable to add to HttpContext.Request or Response cookies collection.

I am using Moq. Also I am using MvcMockHelp from the following link: http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx

When I try to add to Cookies collection in my following code:

        HttpContextBase c1 = MvcMockHelpers.FakeHttpContext();
        HttpCookie aCookie = new HttpCookie("userInfo");
        aCookie.Values["userName"] = "Tom";
        c1.Request.Cookies.Add(aCookie);    <------ Error here

I get the following error on the 4th line of code c1.Request.Cookies.Add(aCookie);

Object reference not set to an instance of an object.

I have also tried instantiating context object as follows but still no luck

HttpContextBase c = MvcMockHelpers.FakeHttpContext
             ("~/script/directory/NAMES.ASP?city=irvine&state=ca&country=usa");

I see that Cookies collection inside Request is NULL. How do I instantiate it?

I have also tried the following but no luck.

c1.Request.Cookies["userName"].Value = "Tom";

Please let me know what am I doing wrong.

Answer

nicodemus13 picture nicodemus13 · Apr 7, 2012

Looking at Hansleman's code, the Request property is created as a Mock, however, the properties of that mock aren't setup, so that's why Cookies is null, and you can't set it, as it's a read-only property.

You have two options:

  1. Setup the mock of the Cookies property in the FakeHttpContext() method, or
  2. If you don't want to do that, say you're referencing the library directly, then you can simply reconstitute the mocked HttpRequestBase from the HttpContextBase you have access to, like so:

    [Test]
    public void SetCookie()
    {
      var c1 = MvcMockHelpers.FakeHttpContext();
      var aCookie = new HttpCookie("userInfo");
      aCookie.Values["userName"] = "Tom";
    
      var mockedRequest = Mock.Get(c1.Request);
      mockedRequest.SetupGet(r => r.Cookies).Returns(new HttpCookieCollection());
      c1.Request.Cookies.Add(aCookie);
    
      Debug.WriteLine(c1.Request.Cookies["userInfo"].Value);
    }
    

    Mock.Get(object) will return you the Mock, then you can setup you cookies on it and use it.

In general you can recreate an Object into its Mock by using the static method Get(MockedThing.Object)