How to mock ModelState.IsValid using the Moq framework?(如何使用 Moq 框架模拟 ModelState.IsValid?)
问题描述
我正在我的控制器操作方法中检查 ModelState.IsValid
,该方法会创建这样的 Employee:
I'm checking ModelState.IsValid
in my controller action method that creates an Employee like this:
[HttpPost]
public virtual ActionResult Create(EmployeeForm employeeForm)
{
if (this.ModelState.IsValid)
{
IEmployee employee = this._uiFactoryInstance.Map(employeeForm);
employee.Save();
}
// Etc.
}
我想在我的单元测试方法中使用 Moq 框架来模拟它.我试着像这样模拟它:
I want to mock it in my unit test method using Moq Framework. I tried to mock it like this:
var modelState = new Mock<ModelStateDictionary>();
modelState.Setup(m => m.IsValid).Returns(true);
但这会在我的单元测试用例中引发异常.有谁能帮帮我吗?
But this throws an exception in my unit test case. Can anyone help me out here?
推荐答案
你不需要模拟它.如果您已经有控制器,则可以在初始化测试时添加模型状态错误:
You don't need to mock it. If you already have a controller you can add a model state error when initializing your test:
// arrange
_controllerUnderTest.ModelState.AddModelError("key", "error message");
// act
// Now call the controller action and it will
// enter the (!ModelState.IsValid) condition
var actual = _controllerUnderTest.Index();
这篇关于如何使用 Moq 框架模拟 ModelState.IsValid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Moq 框架模拟 ModelState.IsValid?


基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01