I've been using TDD for several months, now I would like to learn how to test my Controllers (MVC).
Unit tests are made by testing the smallest unit of each functionality. Sometimes, controllers aren't small. They grab data from Models and pass then to the views.
How should I unit test a Controller? Should I mock controller's dependencies?
Are controllers tests considered integration tests?
Thank you.
Controllers have to be tested, this was one of the goals of MVC framework - Make those stuff testable. For small applications that approach works really well. Almost all logic is placed inside controller, everything very nicely tested.
Yeah I think it does. The unit tests will test individual functionality and also provide you with a means to test if the unit was broken when other code changed. The integration test then tests the end-to-end process.
Controller methods should be unit tested using assert for REST HTTP Status code. Use the HttpStatusCode enum type to Assert the responses. Assert. IsType<OkObjectResult>(result);
I'm doing TDD for quite long time. I'm doing TDD with ASP.NET MVC for more than year now.
I started with canonical rules: "no line of code without unit tests", so I tested everything - including the controllers. Controllers have to be tested, this was one of the goals of MVC framework - Make those stuff testable.
For small applications that approach works really well. Almost all logic is placed inside controller, everything very nicely tested.
But as long as I continued with MVC I started to change my mind. I try to keep controllers as slim as possible. Ideally nothing more as delegating the call to some business object and wrapping the results. The rest is by filters.
That worked nicely for me as well! I'm having now business object that are implemented/tested separately, so the controller is just integration point. No reason to test integration point since it is to small.
Regarding the integration tests: I haven't yet met the situation, where I actually need that. Don't forget, that controllers are always depend on abstractions that you inject by constructor. As long as you have 'good' assumptions how these abstractions work, you create proper unit tests. As you failed, you just correct the unit tests.
Integration tests are important and useful, but I try to create those as few as possible.
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