Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a HttpResponse in Asp.NetCore controller?

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?

like image 990
Rhaegar Cheng Avatar asked Sep 05 '25 16:09

Rhaegar Cheng


1 Answers

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.

like image 138
Nkosi Avatar answered Sep 07 '25 09:09

Nkosi