ModelState.IsValid is being set to true when the properties are incorrect. I've decorated the fields with Requied, Minimum/MaxLength etc however the ModelState.IsValid bool is returning as true.
Is this because im skipping the model binding as i'm testing and it doesnt actually perform validation?
[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.
}
Any idea why? I expect the result3 to be of ViewResult and the ViewName to be "AddProject" because ModelState.IsValid bool should be false. Why? :(