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.
Answer: In an MVC application, all the features are based on interface. So, it is easy to unit test a MVC application. And it is to note that, in MVC application there is no need of running the controllers for unit testing.
You can either create a unit test project when creating your application or add a unit test project to an existing application. This tutorial shows both methods for creating a unit test project. To follow this tutorial, you can use either approach.
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);
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With