views:

85

answers:

1

I know this has been asked before but I can't find it so...

Say I have a controller called HomeController and it has an action called Login.

My Login action takes a model called LoginFormViewModel.

Inside my action I can write code like;

    public ActionResult Login(LoginFormViewModel loginFVM)
    {
        if (ModelState.IsValid)
        {
            return RedirectToAction("provider");
        }

        return View(loginFVM);
    }

What I want is to write a test which will allow me to pass in a form view model and detect whether it's valid or not and thus assert the result.

EDIT

I think I may have confused the issue a bit.

On my model I have some validation that checks that the user name is filled in and that the password conforms to our requirements.

So what I'm testing is whether the model validated ok and I thought I'd do that by executing the View as that is what will happen in real life.

So essentially I'm going to create a model that should fail the ModelState.IsValid test and I want to be able to chech that within my test.

If there is a better way then I'd love to have it.

+1  A: 

If you are testing to make sure your model is passed through to the view correctly:

[Test]
public void Login_Should_Set_Model()
{
    var controller = new HomeController();
    var model = CreateMockLoginFormViewModel();
    var result = controller.Login(model) as ViewResult;

    Assert.AreEqual(model, result.ViewData.Model);
}

UPDATE Since the OP is interested in testing whether or not MVC is validating the model, I found this link that may help: Testing DataAnnotation-based validation in ASP.NET MVC

HackedByChinese
Thanks @HackedByChinese but could you check my edit.
griegs
I see. I think the issue here is whether or not you should be testing MVC's ability to perform validation. It may be more appropriate for you to pick a compatible validation framework and technique, and focusing instead on putting validation on your models and testing *that* directly, rather than the plumbing of MVC. I could be wrong, though.
HackedByChinese
I hear what you say but I'd really like to test on a view by view basis and pass in models that may pass or fail. +1 for your solution here as I think I can use it elsewhere.
griegs
I updated my answer. Perhaps the link I found will help some.
HackedByChinese
Thats it! Thank you.
griegs