There are basically two ways of doing this.
Assuming you are using .NET 3.5 or up. Change your implementation to take the HttpSessionStateBase object as a constructor parameter, you can then mock this implementation - there's a few tutorials online on how to do this. You can then use an IoC container to wire this up at app start or do something like (poor man's dependency injection):
public class MyObjectThatUsesSession
{
HttpSessionStateBase _session;
public MyObjectThatUsesSession(HttpSessionStateBase sesssion)
{
_session = session ?? new HttpSessionStateWrapper(HttpContext.Current.Session);
}
public MyObjectThatUsesSession() : this(null)
{}
}
Alternatively, and probably a bit better and more flexible design would be to create a test seam by wrapping your interaction with session in another object. You could then change this to a database, cookie or cache based implementation later. Something like:
public class MyObjectThatUsesSession
{
IStateStorage _storage;
public MyObjectThatUsesSession(IStateStorage storage)
{
_storage= storage ?? new SessionStorage();
}
public MyObjectThatUsesSession() : this(null)
{}
public void DoSomethingWithSession()
{
var something = _storage.Get("MySessionKey");
Console.WriteLine("Got " + something);
}
}
public interface IStateStorage
{
string Get(string key);
void Set(string key, string data);
}
public class SessionStorage : IStateStorage
{
//TODO: refactor to inject HttpSessionStateBase rather than using HttpContext.
public string Get(string key)
{
return HttpContext.Current.Session[key];
}
public string Set(string key, string data)
{
HttpContext.Current.Session[key] = data;
}
}
You can then use Moq to create a mock IStateStorage implementation for your tests or create a simple dictionary based implementation.
Hope that helps.