Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error trying to create Mock.Of<ControllerContext>() for ASP.Net Core 3.1 Unit Test

As per last section of the Moq Quickstart defined here, I am trying to configure the following Mock in order to pass Form values to the controller method under test:

var formCollection = new FormCollection(
                new System.Collections.Generic.Dictionary<string, Microsoft.Extensions.Primitives.StringValues>()
            {
                    {"mAction", "someAction" },
                    {"mRefId", "0" }
            });

        var controllerContext = Mock.Of<ControllerContext>(ctx =>
            ctx.HttpContext.Request.Form == formCollection);
        
        controller.ControllerContext = controllerContext;

However, when the run the test, it fails on the Mock.Of<> line with the following error:

System.NotSupportedException : Unsupported expression: mock => mock.HttpContext

Non-overridable members (here: ActionContext.get_HttpContext) may not be used in setup / verification expressions.

What am I missing? Am I not doing it the same as per the example defined in the Quickstart document?

like image 889
Shawn de Wet Avatar asked Oct 27 '25 06:10

Shawn de Wet


1 Answers

The error is because ControllerContext.HttpContext property is not virtual, so Moq is unable to override it.

Consider using an actual ControllerContext and mocking a HttpContext to assign to the property

var formCollection = new FormCollection(new Dictionary<string, StringValues>()
    {
        {"mAction", "someAction" },
        {"mRefId", "0" }
    });

var controllerContext = new ControllerContext() {
    HttpContext = Mock.Of<HttpContext>(ctx => ctx.Request.Form == formCollection)
};

controller.ControllerContext = controllerContext;

//...

Or even using DefaultHttpContext and assign the desired value(s)

var formCollection = new FormCollection(new Dictionary<string, StringValues>()
    {
        {"mAction", "someAction" },
        {"mRefId", "0" }
    });

HttpContext httpContext = new DefaultHttpContext();
httpContext.Request.Form = formCollection;

var controllerContext = new ControllerContext() {
    HttpContext = httpContext
};

controller.ControllerContext = controllerContext;

//...
like image 150
Nkosi Avatar answered Oct 29 '25 18:10

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!