尝试为 ASP.Net Core 3.1 单元测试创建 Mock.Of<ControllerContext>() 时出错 [英] Error trying to create Mock.Of<ControllerContext>() for ASP.Net Core 3.1 Unit Test
问题描述
根据在 此处 定义的 Moq 快速入门的最后一部分,我正在尝试配置以下 Mock 以将 Form 值传递给被测控制器方法:
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;
然而,当运行测试时,它在 Mock.Of<>
行上失败并出现以下错误:
However, when the run the test, it fails on the Mock.Of<>
line with the following error:
System.NotSupportedException : 不支持的表达式:mock =>mock.HttpContext
System.NotSupportedException : Unsupported expression: mock => mock.HttpContext
不可覆盖的成员(此处:ActionContext.get_HttpContext)不得用于设置/验证表达式.
Non-overridable members (here: ActionContext.get_HttpContext) may not be used in setup / verification expressions.
我错过了什么?我是不是按照 Quickstart 文档中定义的示例进行操作?
What am I missing? Am I not doing it the same as per the example defined in the Quickstart document?
推荐答案
错误是因为 ControllerContext.HttpContext
属性不是虚拟
,因此 Moq 无法覆盖它.
The error is because ControllerContext.HttpContext
property is not virtual
, so Moq is unable to override it.
考虑使用实际的 ControllerContext
并模拟一个 HttpContext
以分配给属性
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;
//...
甚至使用 DefaultHttpContext
并分配所需的值
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;
//...
这篇关于尝试为 ASP.Net Core 3.1 单元测试创建 Mock.Of<ControllerContext>() 时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!