本文介绍了如何使用起订量框架嘲笑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.
}
我要嘲笑它在我使用起订量框架的单元测试方法。我试图嘲弄它是这样的:
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();
这篇关于如何使用起订量框架嘲笑ModelState.IsValid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!