Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I test my controllers (MVC)?

Tags:

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.

like image 227
user972959 Avatar asked Apr 18 '12 13:04

user972959


People also ask

Do controllers need to be tested?

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.

Does it make sense to unit test controllers?

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.

What is a best practice when unit testing a controller?

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);


1 Answers

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.

like image 83
Alexander Beletsky Avatar answered Sep 22 '22 04:09

Alexander Beletsky