Tips and Tricks for Unit Testing Your ASP.NET MVC Application

Now that you have the necessary tools in your belt, let's take a closer look at some of the more common unit testing tasks in ASP.NET MVC applications.

Testing Controllers

The default unit test project already includes some controller tests (which you modified earlier in this chapter). A surprising number of subtleties are involved with testing controllers, and as with all things, the subtleties between decent and great code can often be found in small differences.

Keep Business Logic out of Your Controllers

The primary purpose of a controller in a Model-View-Controller architecture is to be the coordinator between the model (where your business logic lives) and the view (where your user interface lives). The controller is the dispatcher that wires everybody together and gets everybody running.

When we talk about business logic, it could be something as simple as data or input validation, or something as complex as applying long-running processes like core business workflow. As an example, controllers shouldn't try to validate that models are correct; that is the purpose of the business model layer. It does, however, need to concern itself with what actions to take when it has been told that the model isn't valid (perhaps re-displaying a particular view when it's invalid, or sending the user off to another page when the model is valid).

Because your controller action methods will be relatively simple, the unit tests ...

Get Professional ASP.NET MVC 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.