Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking HttpResponseHeaders and cookies in WebAPI

I'm trying to write some unit tests for my web api controller, and I need to test that a cookie is being retrieved correctly so I want to setup a mock that returns the cookies I want to test for. Cookies are retrieved like so in WebAPI:

Request.Headers.GetCookies("CookieName").FirstOrDefault()

The request object is mockable but unfortunately I cannot mock the headers property (which is a HttpRequestHeaders object) as HttpRequestHeaders is sealed and none of its methods are virtual, and it also doesn't implement an interface (good job MS).

Is there any way to mock the getting / setting of cookies in WebAPI or not?

p.s. I don't want to hear that I should not be using cookies in WebAPI, that's what is being done and to change it is outside the scope of my current work

like image 341
jcvandan Avatar asked Dec 02 '15 14:12

jcvandan


1 Answers

This is what i ended up doing.

To set the Request cookies.

  var target = new YourController()
  target.Request.Headers.Add("Cookie", "YourCookieKey=Value;");

To read the Response cookie.

 var response = target.YourControllerMethod();
 var result = response.Content.ReadAsAsync<YourModel>().Result;
 Assert.IsTrue(response.Headers.GetValues("Set-Cookie").ToList()[0].Contains("YourCookieKey"));
like image 178
Sush Avatar answered Nov 07 '22 21:11

Sush