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。爲什麼? :(