0

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? :(

1 Answers1

0

Found the solution. Validation happens when the data that is posted is bound to view model. This is being skipped when ibis passed straight into the controller. The viewmodel is what is passed into the controller and once the model is posted and bound is when the validation is checked, well before it goes into the controller, thats why break pointing in the code will never break when testing the form, because it doesnt even reach the controller.

Hope that made sense if you ever have a similar problem.