Add cookie to Request.Cookies collection Add cookie to Request.Cookies collection asp.net asp.net

Add cookie to Request.Cookies collection


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)