从单元测试调用时,ASP.NET MVC 不会添加 ModelError
我有一个模型项
public class EntryInputModel
{
...
[Required(ErrorMessage = "Description is required.", AllowEmptyStrings = false)]
public virtual string Description { get; set; }
}
和一个控制器操作
public ActionResult Add([Bind(Exclude = "Id")] EntryInputModel newEntry)
{
if (ModelState.IsValid)
{
var entry = Mapper.Map<EntryInputModel, Entry>(newEntry);
repository.Add(entry);
unitOfWork.SaveChanges();
return RedirectToAction("Details", new { id = entry.Id });
}
return RedirectToAction("Create");
}
当我在单元测试中创建 EntryInputModel
时,将 Description
属性设置为 null
并将其传递给操作方法,我仍然得到 ModelState.IsValid == true
,即使我已经调试并验证了 newEntry.Description == null
。
为什么这不起作用?
I have a model item
public class EntryInputModel
{
...
[Required(ErrorMessage = "Description is required.", AllowEmptyStrings = false)]
public virtual string Description { get; set; }
}
and a controller action
public ActionResult Add([Bind(Exclude = "Id")] EntryInputModel newEntry)
{
if (ModelState.IsValid)
{
var entry = Mapper.Map<EntryInputModel, Entry>(newEntry);
repository.Add(entry);
unitOfWork.SaveChanges();
return RedirectToAction("Details", new { id = entry.Id });
}
return RedirectToAction("Create");
}
When I create an EntryInputModel
in a unit test, set the Description
property to null
and pass it to the action method, I still get ModelState.IsValid == true
, even though I have debugged and verified that newEntry.Description == null
.
Why doesn't this work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为当您从测试调用操作时不会发生模型绑定。模型绑定是将发布的表单值映射到类型并将其作为参数传递给操作方法的过程。
This is because model binding doesn't take place when you invoke an action from a test. Model binding is the process of mapping posted form values to a type and pass it as a parameter to an action method.