我正在检查我的 Controller 操作方法中的 ModelState.IsValid
,它创建了这样一个 Employee:
[HttpPost]
public virtual ActionResult Create(EmployeeForm employeeForm)
{
if (this.ModelState.IsValid)
{
IEmployee employee = this._uiFactoryInstance.Map(employeeForm);
employee.Save();
}
// Etc.
}
我想使用 Moq 框架在我的单元测试方法中模拟它。我试着像这样模拟它:
var modelState = new Mock<ModelStateDictionary>();
modelState.Setup(m => m.IsValid).Returns(true);
但这会在我的单元测试用例中引发异常。有人可以帮我吗?
最佳答案
你不需要 mock 它。如果您已经有 Controller ,则可以在初始化测试时添加模型状态错误:
// 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();
关于c# - 如何使用 Moq 框架模拟 ModelState.IsValid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3822873/