views:

90

answers:

2

It seems to me that web developers of different programming languages often share different opinions on this. For example, Ruby web developers (with Rails being the dominant framework) appear to think of controllers as glue code, which should have functional tests, but not unit tests. A similar attitude dominates in the PHP world, yet there has been some initiative (e.g. Symfony2).

However, it also seems that, for example, some ASP.NET MVC developers actually want their controllers to be unit-testable.

What I'd like to know is if that actually works in web development. Are controllers worth unit testing? Does designing them to be unit-testable noticeably cripple development speed in non-trivial applications? Also, have any web frameworks tried to enforce controller unit-testability? Personal experiences are welcome.

+2  A: 

Everything is worth to be unit tested. In this case it depends on how much of the logic is realized in the controllers... In small project you can have no external logic attached and you may want to make some of the database operations in your controller (like on many Microsoft examples). In bigger solutions you may not need to test the controller as far as it's job is just to invoke specified business logic methods... It's not about if controllers are worth to be unit tested, it's about if the code that they contains is...

ŁukaszW.pl
+2  A: 

Short answer: "Yes" with an "If," long answer: "No" with a "But."

These days I tend to miss controller-level unit tests in favour of strong unit-test coverage of models and business objects and functional-test coverage with Cucumber. The assumption here is that the controllers are very light-weight objects routing data into underlying models that encapsulate the vast majority of business logic.

However, I still do tend to have some very light coverage of some of the control flow at the controller level. It just tends to be more of a sanity-check.

One of the issues with controller-level testing is that you often either have to mock or generate a large number of models and objects in order to test effectively. Given this, I find it more valuable to push these tests up into the functional layers where the style of testing allows you to more efficiently express these dependencies (either by explicitly following the steps required to generate them through your application itself or through a system like Cucumber's declarative rules).

Toby Hede