gpt4 book ai didi

c# - 尝试为 ASP.Net Core 3.1 单元测试创​​建 Mock.Of() 时出错

转载 作者:行者123 更新时间:2023-12-04 01:29:48 25 4
gpt4 key购买 nike

根据 Moq 快速入门的最后一部分定义 here ,我正在尝试配置以下 Mock,以便将 Form 值传递给被测 Controller 方法:

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<> 上失败了。出现以下错误的行:

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

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


我错过了什么?我是否按照 Quickstart 文档中定义的示例进行操作?

最佳答案

错误是因为 ControllerContext.HttpContext 属性不是 virtual ,因此 Moq 无法覆盖它。
考虑使用实际 ControllerContext 并 mock HttpContext分配给属性(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并分配所需的值
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;

//...

关于c# - 尝试为 ASP.Net Core 3.1 单元测试创​​建 Mock.Of<ControllerContext>() 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61269967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com