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
Unit testing ensures that all code meets quality standards before it's deployed. This ensures a reliable engineering environment where quality is paramount. Over the course of the product development life cycle, unit testing saves time and money, and helps developers write better code, more efficiently.
We create the data access logic in a separate class, or set of classes, called a repository, with the responsibility of persisting the application's business model. As the Repository Pattern is useful for decoupling entity operations from presentation, it allows easy mocking and unit testing.
A controller is responsible for controlling the way that a user interacts with an MVC application. A controller contains the flow control logic for an ASP.NET MVC application. A controller determines what response to send back to a user when a user makes a browser request.
In computer programming, unit testing is a software testing method by which individual units of source code are tested to determine whether they are fit for use.
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With