Some people argue that there is no value in testing MVC Controllers as they should not be housing any complex logic. These people would argue that, at most, MVC Controllers should be tested as part of integration testing, but shouldn’t warrant unit testing.

Obviously, if all you’re doing is integration testing then there probably isn’t much call for mocking, but I would argue that there are valid reasons for unit testing MVC Controllers…

  • Ensuring that correct view/view model is returned for each Action;
  • Ensuring that all relevant mocked domain logic components are invoked;
  • Ensuring that all expected validation errors are raised and returned in the ActionResult;
  • Ensuring that functionality sometimes implemented at Controller level (such as sorting and some elements of paging) are working as expected.

Any form of testing should always fall under the constraints of the Law of Diminishing Returns, and so we shouldn’t test MVC Controllers for the sake of it. However, if we’re smart about how we structure our tests we should have pretty good coverage with minimal test-writing required.

So with the justification out of the way — not that we needed justification, ‘cos writing tests is fun, right? (right?) — we are now faced with the problem of mocking all the dependencies we need to test a Controller. This, as you may imagine, is not simple, with all the Request contexts, Server contexts, Identity contexts, etc. Fortunately for you, I have been through the pain and have found all the things that need to be mocked and how to mock them in order to have a testable MVC Controller with all the contextual elements present and accounted for…

Note: The below example is dependent upon my ArrangeActAssert Test Class Structure.