MVCContrib contains an assembly specifically built to provide help when unit testing ASP.Net MVC controller actions. This is a very condensed guide to what you can accomplish using each helper method.
Test View Rendering
Test that a view is being rendered from the action:
_controller.List().AssertViewRendered();
…for a particular view
_controller.List().AssertViewRendered().ForView("SomeViewName");
…with a view model of the correct type
_controller.List().AssertViewRendered().ForView("List").WithViewData<SomeType>();
Test PartialView Rendering
Test that a partial view is being rendered from the action:
_controller.ShowAsteroid().AssertPartialViewRendered();
…for a particular view
_controller.ShowAsteroid().AssertPartialViewRendered().ForView("Asteroid");
…with a view model of the correct type
_controller.ShowAsteroid().AssertPartialViewRendered().ForView("Asteroid").WithViewData<AsteroidModel>();
Test Redirects
Assert that the action redirects to the correct action:
_controller.AddFormStar().AssertActionRedirect().ToAction("List");
…for an action on a different controller:
_controller.AddFormStar().AssertActionRedirect().ToController("SomeController").ToAction("List");
Easily Stub HttpContext Variables
The TestHelper library contains a class (TestControllerBuilder) that builds up a complete context for your controller to operate within. This gives you the ability to easily mock anything that you would normally access from HttpContext. Here’s an example of usage:
The _builder variable is what contains all of the dictionaries for Session, ViewData, etc. that you can use to set up all of your stubs. Example:
The code in the ActionUnderTest method will now be able to access all of the variables just set up in the test. Couldn’t be easier!
2 comments:
Thanks for this post!
This is gonna simplify controller testing. I have been looking for something like this since I started developing MVC applications.
Charles
Thanks for the post. It was really helpful. I have started using MVCContrib TestHelpers. This post was a good starting point.
Post a Comment