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.
Thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 😉