2015-09-27 59 views
0

當屬性不​​正確時,ModelState.IsValid被設置爲true。我用Requied,Minimum/MaxLength等來裝飾字段,但ModelState.IsValid布爾返回爲true。爲什麼我的模型驗證不正確?

這是因爲我跳過模型綁定,因爲我測試,它不實際執行驗證?

[Authorize(Roles = "A")] 
[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult AddProject(Projects project) 
{ 
    if (project == null) 
    { 
     return HttpNotFound(); 
    } 

    if (ModelState.IsValid) 
    { 
     using (var db = new DbContext()) 
     { 
      db.ProjectModels.Add(project); 
      db.SaveChanges(); //exception raised here. 
     } 
     return RedirectToAction("ListOfProjects", "Project"); 
    } 
    return View("AddProject", project); 
} 

[TestMethod()] 
public void AddProjectTestWithModel() 
{ 
    //initialize 
    var controller = new AdminController(); 
    var model = new Projects() 
    { 
     Name = "Project", 
     Description = "Description", 
     Duration = "1 Month" 
    }; 
    var nullModel = new Projects(); 
    nullModel = null; 
    var invalidModel = model; 
    invalidModel.Description = null; 
    invalidModel.Name = null; 

    //setup 
    var result = (RedirectToRouteResult)controller.AddProject(model) as RedirectToRouteResult; 
    var modelFromDb = db.ProjectModels.Find(model.Id); 
    var result2 = (HttpNotFoundResult)controller.AddProject(nullModel) as HttpNotFoundResult; 
    var result3 = (ViewResult)controller.AddProject(invalidModel) as ViewResult; 

    Assert.AreEqual("ListOfProjects", result.RouteValues["action"]); 
    Assert.AreEqual(404, result2.StatusCode); 
    Assert.AreEqual("AddProject", result3.ViewName); //UnitTest fails here. 
} 

任何想法爲什麼?我期望result3是ViewResult和ViewName是「AddProject」,因爲ModelState.IsValid布爾應該是false。爲什麼? :(

回答

0

找到了解決方案:當發佈的數據綁定到視圖模型時,驗證發生,當ibis直接進入控制器時,會跳過此視圖模型,傳遞到控制器中,一旦模型發佈和綁定的時候,驗證檢查時,以及它進入控制器之前,這就是爲什麼在測試表單時,斷點指向永遠不會中斷,因爲它甚至不會到達控制器。你曾經有過類似的問題

相關問題