Is it possible to unit test some AddModelError results in ASP.NET MVC?

2.2k views Asked by At

I've got a controller method which returns a RedirectToActionResult (success!) or a ViewResult (failed with error messages).

If the business logic fails, i add the error messages to the AddModelError property.

Is there any way i can test this in my MS Unit tests? I also have Moq, if that helps too. (i don't believe Moq is required for this scenario though) .. I'm not using anything from the Request object.

2

There are 2 answers

0
Pure.Krome On

Yep, figured it out.

// Arrange.
// .. whatever ..

// Act.
var viewResult = controller.Create(new Post()) as ViewResult;

// Assert.
Assert.IsNotNull(viewResult);
Assert.IsNotNull(viewResult.ViewData.ModelState["subject"]);
Assert.IsNotNull(viewResult.ViewData.ModelState["subject"].Errors);
Assert.IsTrue(viewResult.ViewData.ModelState["subject"].Errors.Count == 1);
0
Jonathan On

You can (also) test the Controller directly (without testing the View) as follows:

// Arrange.
// .. 

// Act.
controller.Create(new Post());  // missing UserName will invalidate Model with "Please specify your name" message

// Assert
Assert.IsTrue(! controller.ModelState.IsValid);
Assert.IsTrue(  controller.ModelState["UserName"].Errors.Any( modelError => modelError.ErrorMessage == "Please specify your name"));