O'Reilly logo

Professional ASP.NET MVC 3 by K. Scott Allen, Brad Wilson, Phil Haack, Jon Galloway

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required