Add cookie to Request.Cookies collection

I am trying to create a wrapper class to handle the contents of an HttpContext. I am creating a cookie but cannot add it to the HttpContext.Request or Response files collection.

I am using Moq. I also use MvcMockHelp at the following link: http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx

When I try to add cookies to my 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 in the 4th line of code c1.Request.Cookies.Add (aCookie);

 Object reference not set to an instance of an object. 

I also tried to instantiate the 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 the Cookies collection inside the request is NULL. How to create it?

I also tried the following, but no luck.

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

Please let me know what I am doing wrong.

+7
source share
1 answer

Looking at the Hansleman code, the Request property is created as a Mock , however the properties of this layout are not configured, so Cookies is null and you cannot set it, since this property is read-only.

You have two options:

  • Set the layout of the Cookies property in the FakeHttpContext() method or
  • If you do not want to do this, say that you are directly referencing the library, you can simply restore the mocked HttpRequestBase from the HttpContextBase that you have access to, for example:

     [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 Mock to you, then you can set your cookies on it and use it.

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

+8
source

All Articles