MVC Advantages of Unit Testing Controllers

My application already has unit test for domain layer I would like to know what are the pros/cons of unit testing controller

and what test cases should one write when testing controllers.



It depends.

Validation, redirection, temporary messages and so on can occur in controllers. You could argue these operations should be tested as you would your models.

On the other hand, you should be aiming for the 'Fat Model, Skinny Controller' mindset. I tend to make sure my controllers are as dumb as possible. Put a few end to end tests around the features you care about (Selenium, Cucumber etc...) and these will enforce that your controllers are correct. Say we were developing a feature to list some items. If the end to end test of this feature is fine, the controller is fine. If this breaks you'll know you've introduced a regression. In combination to this I only have tests that check the correct views are rendered and the correct response occurs - redirection, json etc... Any more testing on your controller and you have logic in the wrong place.

In ASP.NET MVC2 by Steve Sanderson he makes some excellent points about the above reasoning. I fully recommend it. The con to not having these simple controller tests is I could easily open your codebase, make a simply change and break your app. As long as the correct views/responses occur the app will still be functionally intact.

I should add that testing a service is invoked within a controller with the correct parameters is so trivial, and quick to do you may as well do this whether or not you test your controllers indirectly. I tend to favour this approach overall. So the full answer to your question is yes, test your controllers ;)

Need Your Help

Why is this HashMap being passed as reference

java hashmap

I have two HashMaps defined as follows:

Writing log to a “lock for edit” file, which throws exception. How to fix this?

c# logging

I have multithreaded operation running, each one append some info to my log file. The problem is, sometimes log file is locked for editing and at the same time is accessed by other thread, which th...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.