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 ViewMod开发者_StackOverflow中文版el, 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?
mock the HttpContext is a huge work as it is one of the biggest object you will see in all your life so probably is better don't mock it.(http://volaresystems.com/Blog/post/Dont-mock-HttpContext.aspx) Anyway you could use the one in MVCcontrib (http://www.codeplex.com/mvcContrib) the file MvcMockHelps shows how it is done.
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.
精彩评论