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?


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01