MVC Runtime already provides an HttpContextWrapper . What you need to implement is a wrapper around the session state and encapsulates the fact of accessing the state through HttpContextso that you can use the DI or the Mocking framework to create an unconverted SessionWrapper HttpContextfor your tests. Brad Wilson gives some good information on how to do this . However, if you do not want to wade through a video (containing advanced topics), here is the gist for a session session:
Create an interface representing a strongly typed object, which you can usually access through a session:
public interface ISessionWrapper
{
public UserPreferences CurrentUserPreferences{get;set;}
...
}
Create an implementation of an interface that uses Session as the backup storage:
public class HttpContextSessionWrapper : ISessionWrapper
{
private T GetFromSession<T>(string key)
{
return (T) HttpContext.Current.Session[key];
}
private void SetInSession(string key, object value)
{
HttpContext.Current.Session[key] = value;
}
public UserPreferences CurrentUserPreferences
{
get { return GetFromSession<UserPreferences>("CurrentUserPreferences"); }
set { SetInSession("CurrentUserPreferences", value); }
}
...
}
Controller DependencyResolver (, , DI). , SessionWrapper , BaseController:
var SessionWrapper = DependencyResolver.Current.GetService<ISessionWrapper>();