Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it really necessary to test controller methods?

When I design MVC apps, I typcially try to keep almost all logic (as much as possible) out of my app. I try to abstact this into a service layer which interfaces with my repositories and domain entities.

So, my controller methods end up looking something like this:

public ActionResult Index(int id)
{
    return View(Mapper.Map<User, UserModel>(_userService.GetUser(id)));
}

So assuming that I have good coverage testing my services, and my action methods are simple like the above example, is it overkill to unit test these controller methods?

If you do build unit tests for methods that look like this, what value are you getting from your tests?

like image 235
Jerad Rose Avatar asked Jan 26 '26 10:01

Jerad Rose


1 Answers

If you do build unit tests for methods that look like this, what value are you getting from your tests?

You can have unit tests that assert:

  1. That the GetUser method of the _userService was invoked, passing the same int that was passed to the controller.
  2. That the result returned was a ViewResult, instead of a PartialViewResult or something else.
  3. That the result's model is a UserModel instance, not a User instance (which is what gets returned from the service).

Unit tests are as much a help in refactoring as asserting the correctness of the application. Helps you ensure that the results remain the same even after you change the code.

For example, say you had a change come in that the action should return a PartialView or JsonResult when the request is async/ajax. It wouldn't be much code to change in the controller, but your unit tests would probably fail as soon as you changed the code, because it's likely that you didn't mock the controller's context to indicate whether or not the request is ajax. So this then tells you to expand on your unit tests to maintain the assertions of correctness.

Definitely value added IMO for 3 very simple methods which shouldn't take you longer than a couple of minutes each to write.

like image 99
danludwig Avatar answered Jan 28 '26 23:01

danludwig