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?
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;
//...
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