I am working on a Asp.NetCore application, and one of the controllers looks like this:
[HttpPost, Route("setCookies")]
public int SetCookies([FromBody] Dictionary<string, string> cookies)
{
foreach (var cookie in cookies)
{
Response.Cookies.Append(cookie.Key, cookie.Value, new CookieOptions() { Path = "/", HttpOnly = true });
}
return 1;
}
And now I am trying to add unit test case for this controller.
After I create an instance of the controller by
var _controller = new Controller();
and call the method
_controller.SetCookies(<some parameter>);
It shows that Response
is null.
I checked the metadate and it shows that Response
is a readonly property in the abstract base class ControllerBase
like this:
public HttpResponse Response { get; }
So, is there anyway to mock the Response
property?
The request and response are associated with the controller's current HttpContext
, which you will need to set via the ControllerContext
when setting up the controller.
//...
//Arrange
HttpContext httpContext = new DefaultHttpContext();
//Controller needs a controller context
var controllerContext = new ControllerContext() {
HttpContext = httpContext,
};
//assign context to controller
var _controller = new MyController(){
ControllerContext = controllerContext,
};
//Act
int actual = _controller.SetCookies(<some parameter>);
//...
The DefaultHttpContext
used in the example above, will have a non-null empty request and response by default. This should give you access to the response to exercise your unit test as desired.
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