当属性不正确时,ModelState.IsValid被设置为true。我用Requied,Minimum / MaxLength等装饰了字段,但ModelState.IsValid bool返回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 bool应该是false。为什么? :(
答案 0 :(得分:0)
找到解决方案。当发布的数据绑定到查看模型时,将进行验证。当ibis直接进入控制器时,这将被跳过。 viewmodel是传递给控制器的东西,一旦模型发布和绑定是在检查验证之前,在它进入控制器之前,这就是为什么在测试表单时断开指向代码永远不会破坏,因为它不会甚至到达控制器。
希望你有类似的问题是有意义的。