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?


基础教程推荐
- 将数据集转换为列表 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 如果条件可以为空 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01