views:

104

answers:

1

I have a model item

public class EntryInputModel
{
    ...

    [Required(ErrorMessage = "Description is required.", AllowEmptyStrings = false)]
    public virtual string Description { get; set; }
}

and a controller action

public ActionResult Add([Bind(Exclude = "Id")] EntryInputModel newEntry)
{
    if (ModelState.IsValid)
    {
        var entry = Mapper.Map<EntryInputModel, Entry>(newEntry);

        repository.Add(entry);
        unitOfWork.SaveChanges();
        return RedirectToAction("Details", new { id = entry.Id });
    }
    return RedirectToAction("Create");
}

When I create an EntryInputModel in a unit test, set the Description property to null and pass it to the action method, I still get ModelState.IsValid == true, even though I have debugged and verified that newEntry.Description == null.

Why doesn't this work?

A: 

This is because model binding doesn't take place when you invoke an action from a test. Model binding is the process of mapping posted form values to a type and pass it as a parameter to an action method.

uvita
So how do I test that my controller verifies the model state before saving to db?
Tomas Lycken
From your unit test, call ModelState.AddModelError("dummy", "some error text") before executing the method under test.
Levi
Thanks a lot! =)
Tomas Lycken