0
我有一個模型項目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
。
爲什麼不能正常工作?
那麼如何測試我的控制器在保存到db之前驗證模型狀態? – 2010-04-06 03:32:52
在執行被測方法之前,請從您的單元測試中調用ModelState.AddModelError(「dummy」,「some error text」)。 – Levi 2010-04-06 05:19:36