jeudi 28 mai 2015

Why Controller.UpdateModel doesn't validate model with globalized validation attributes from a unit test?

I created an ASP.NET MVC 5 application, with the following model class using a globalized Required validation attribute on its Email property:

public class Person
{
    [Required(ErrorMessageResourceType = typeof(Resources),
              ErrorMessageResourceName = "EmptyEmailError")]
    public string Email { get; set; }
}

The Create POST action method of the PersonController class is:

[HttpPost]
public ActionResult Create(FormCollection formData)
{
    Person newPerson = new Person();
    UpdateModel(newPerson, formData);

    if (ModelState.IsValid) {
        // code to create the new person
        return View("Index", newPerson);
    }
    else {
        return View();
    }
}

And the test case for verifying that a person with an empty e-mail address is not created is:

[TestMethod]
void Create_DoesNotCreatePerson_WhenEmailIsEmpty()
{
    // arrange
    FormCollection person = new FormCollection() { { "Email", string.Empty } };
    PersonController controller = new PersonController();
    controller.ControllerContext = new ControllerContext();

    // act
    controller.Create(person);

    // assert
    Assert.IsFalse(controller.ModelState.IsValid);
}

With this code the normal execution works fine. However, the test doesn't pass, which means that UpdateModel is returning true and thus not validating the person model correctly. The TryUpdateModelmethod doesn't work too.

But if I remove the ErrorMessage arguments from the Required validation attribute in the Person class (i.e. leaving it just as [Required]), then the test passes.

So I don't know why UpdateModel doesn't validate the globalized Person model when I call the Create action method from the test case.

Aucun commentaire:

Enregistrer un commentaire