Mocking the HttpContext.Request object

You’re unit testing a Controller and someone has used the Request object to for example, check headers. You are going to need to mock the Request object for your unit test to run without throwing a null reference error.

This is relatively simple using the code below.

private ControllerContext GetMockedControllerContext(Dictionary<string, string> headers, string scheme = "http")
{
    var controllerContext = new ControllerContext
    {
        HttpContext = new DefaultHttpContext()
    };
    foreach (var (key, value) in headers)
    {
        controllerContext.HttpContext.Request.Headers[key] = value;
    }
    controllerContext.HttpContext.Request.Scheme = scheme;
    return controllerContext;
}

This can be used in the following manner:

var myController = new MyController()
{
    ControllerContext = GetMockedControllerContext(new Dictionary<string, string>())
};

If you need specific headers you can add them by passing in a dictionary, else just pass in an empty dictionary.

Leave a Reply

Your email address will not be published. Required fields are marked *