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
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With