Testing an ActionResult with a Form View Model
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 LoginF开发者_JAVA百科ormViewModel.
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.
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
精彩评论