8

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.

SteveC
  • 15,808
  • 23
  • 102
  • 173
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647

2 Answers2

7

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);
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
6

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"));
Jonathan
  • 1,349
  • 1
  • 10
  • 20