Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add cookie to Request.Cookies collection

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.

like image 436
dotnet-practitioner Avatar asked Apr 06 '12 16:04

dotnet-practitioner


1 Answers

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)

like image 64
nicodemus13 Avatar answered Sep 20 '22 16:09

nicodemus13