我正在我的控制器操作方法中检查 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!