2010-04-06 37 views
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

爲什麼不能正常工作?

回答

0

這是因爲當您從測試中調用某個操作時,模型綁定不會發生。模型綁定是將發佈的表單值映射到類型並將其作爲參數傳遞給動作方法的過程。

+0

那麼如何測試我的控制器在保存到db之前驗證模型狀態? – 2010-04-06 03:32:52

+0

在執行被測方法之前,請從您的單元測試中調用ModelState.AddModelError(「dummy」,「some error text」)。 – Levi 2010-04-06 05:19:36