Excerpted from ASP.NET
MVC in Action
Writing automated tests for all code in a code base is a
best practice. It provides great feedback when the test suite is run multiple
times per day. If you are not doing it now, you should start immediately. You
have several popular, high quality frameworks for automated testing available
to you including NUnit and MbUnit. At the time of writing, NBehave, MSTest and
xUnit are also available, but they do not have nearly the widespread adoption
of NUnit or MbUnit. All of these are free, with the exception of MSTest, which
requires the purchase of Visual Studio, and they make testing code quite
simple. What we are concerned with here in this article is testing controllers.
There are different types of automated testing, and we are concerned with only
one type at this point: unit testing. Unit tests run fast because they do not
call out of process. In a unit test, dependencies are simulated so the only
production code running is the controller code. In order for this to be
possible the controllers have to be well designed. A well designed controller
is loosely coupled with its dependencies. A well designed controller uses
dependencies but is not in charge of locating or creating those dependencies. A
well designed controller has clear responsibilities and only handles logic
relevant to serving a web request. Some things a well designed controller does
not do are file I/O, database access, web service calls, and thread management.
This is not an all-inclusive list, but the listed things make it very
difficult, if not impossible to write an automated unit test for the controller.
The controller may very well call a dependency that does these things, but the
controller itself should only be responsible for interaction with the
dependency, not performing the fine-grained work. This is very important to
testing because good design and testing go hand in hand. It is very difficult
to test poorly designed code. In this article, we will walk through testing our
viewless RedirectController.