In my controller, I have something like this:
public ActionResult Index()
HomeViewModel viewModel = new HomeViewModel();
viewModel.FieldSearchCriteria = new SearchCriteria();
viewModel.Blogs = this.unitOfWork.BlogRepository.GetAllPublishedBlogs(1, 2, "PublishDate", SortDirection.DESC, null).ToList();
viewModel.FieldWanteds = this.unitOfWork.FieldWantedRepository.GetAllFieldWanteds( 1, 2, "CreatedAt", SortDirection.DESC, null ).ToList();
viewModel.Fields = this.unitOfWork.FieldRepository.GetAllFeaturedPublishedFields(1, 4, "CreatedAt", SortDirection.DESC, null).ToList();
viewModel.UserID = User.Identity.GetUserId();
return View( viewModel );
I have placed really specific methods inside my repositories so I can re-use them throughout my application... however I am finding it difficult to get any gains out of unit testing controllers due to not using commands like .Where and .Take inside the controller...
Is it quite normal then to simply test the repository method as a unit test where all the actual stuff I care about testing happens?.. Or am I missing out some bigger picture thing by having all my fetching logic inside the repository methods?
Best How To :
Welcome to chasing the windmill of 100% test coverage :)
You're right, there isn't a ton of value in unit testing a controller method which doesn't actually contain any logic. (Somewhere in the world, Uncle Bob just spilled his coffee.) There is some, though...
- By explicitly defining the expectations (in this case interactions with mocks, basically) then your test will tell you if this method ever changes, which itself is a fact worth knowing. Particularly on larger teams where a rogue mistake can go unnoticed.
- If the test for this method has to be constantly changed because the method itself is under a lot of churn, that's a signal that the method may be responsible to too many roles in the organization or may in some way be a convergence of different responsibilities. That sort of thing can often go unnoticed without good test coverage, and it's a way for bugs to find their way in.
Ultimately it's a judgement call by you, the developer. The cost of writing a test may outweigh the value of having it. (Though, by my second point above, if that cost is high then that itself may be an indication that something is wrong with the design and may require some refactoring... which is easier to do with tests.)
Personally, I'd write a test for this method. It shouldn't have to change, and if it does change I'd want to be painfully aware of that so I can refactor appropriately. Perhaps by moving some of these repository interactions into a single atomic business method which can be tested, leaving a controller action to do nothing but invoke a mock of that business method.