Search code examples
c#asp.net-mvc-3moqviewmodelhttpcontext

Mocking HttpContext in MVC **Outside** of the Controller


Scenario

We're developing a new MVC web project and we're trying to adhere to the Skinny Controller pattern as described in this article http://codebetter.com/iancooper/2008/12/03/the-fat-controller/

As part of one of our actions we are retrieving some navigation data (Menu structure) from the Cache.

Problem

I order to maintain the skinny controller pattern we'd like to have the cache check call in the ViewModel, which we have tried and we know works, using the following code.

var cachedCategories = (List<Category>)HttpContext.Current.Cache["Categories"];
if (cachedCategories == null) {
       cachedCategories = _service.GetCategories().ToList<Category>();
       HttpContext.Current.Cache["Categories"] = cachedCategories;
}

However when it comes to unit testing it we hit a problem. Since we are not directly passing the HttpContext into the ViewModel we have no idea how to go about mocking the HttpContext.

We're using Moq and while we have some options (one is to pass the context from the controller to the viewmodel at instantiation) those options require changing the code purely to make the tests work.

Does anyone have any suggestions?


Solution

  • Ultimately we choose to modify our code to allow for easier testing.

    We accomplished this by passing the HttpContext to the ViewModel at instantiation as I mentioned in my original question.