views:

48

answers:

1

I'm using ASP.NET MVC 2 with DataAnnotation attributes sprinkled on properties like so:

public class LogOnViewModel
{
    [Required]
    public string UserName { get; set; }

    [Required]
    public string Password { get; set; }

    [Required]
    public string Domain { get; set; }
}

I have a unit test which checks that the current view is rendered when validation fails. However, I'm manually adding errors to the ModelState to get it to work:

    [Test]
    public void TestThatLogOnActionRedirectsToLogOnViewIfValidationFails()
    {
        //create a invalid view model
        var model = new LogOnViewModel {UserName = "jsmith"};

        //Can I avoid doing this manually?
        //populate Model State Errors Collection
        _accountController.ModelState.AddModelError("FirstName", "First Name Required");
        _accountController.ModelState.AddModelError("LastName", "Last Name Required");

        var result = _accountController.LogOn(model);

        result.AssertViewRendered()
            .ForView(Constants.Views.LogOn)
            .WithViewData<LogOnViewModel>();
    }

Is there a way to interact with the ModelBinder either directly or indirectly in a unit test? For example:

    [Test]
    public void TestThatLogOnActionRedirectsToLogOnViewIfValidationFails()
    {
        //create a invalid view model
        var model = new LogOnViewModel {UserName = "jsmith"};

        //validate model
        //not sure about the api call...
        var validationResults = new DataAnnotationsModelBinder().Validate(model);

        _accountController.ModelState.Merge(validationResults);
        var result = _accountController.LogOn(model);

        result.AssertViewRendered()
            .ForView(Constants.Views.LogOn)
            .WithViewData<LogOnViewModel>();
    }
+1  A: 

Brad Wilson has a nice blogpost about the DataAnnotationsModelBinder, including how to unit test it: http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html

Dave Cowart
Hi Dave,I found this post after goggling the subject and I wasn't satisfied with his answer of "just trusting" the DataAnnotationsModelBinder so I decided to post a question out here. Thanks Anyway
lcranf