1

I have an asp.net mvc 3 project which has in one of my controllers

Response.Cookies.Add()

When I run some old unit tests they now die on "Response" as it is null. I am not sure how to mock it up to solve this problem.

I seen a couple posts here but none of the solutions seems to work and none talk about "Cookies".

chobo2
  • 83,322
  • 195
  • 530
  • 832

2 Answers2

2
var responseCookies = new HttpCookieCollection();
var mockResponse = Mock.Of<HttpResponseBase>(r => r.Cookies == responseCookies);
//you can use new Mock<>, and the set it up as well, but for simple setups I prefer the above syntax

myTestController.Response = mockResponse;
Sunny Milenov
  • 21,990
  • 6
  • 80
  • 106
  • 1
    The `Response` property is read-only. You need to mock the `ControllerContext ` instead. Have a look at [this answer](http://stackoverflow.com/a/18101855/5844190) – Alsty Mar 31 '16 at 12:03
1

Create class e.g. ResponseProvider which cover this static functionality. In code, you add this class as next dependency and than will call e.g. responseProvider.AddCookie(). In tests, you can use mock object for this ResponseProvider.

Rudis
  • 1,177
  • 15
  • 30