I'm using a Session wrapper as written below. The problem I have is when running tests the try doesn't work and it goes to the catch so session variables are never being set. I'm using Moq to create a mock Session state for my mock context. If I create a variable like:
Session["variable"] = "something";
That works fine and persists to the end of the test. Everything created for in my wrapper does not. Since the Session is somehow persisting, my theory is just that I need to figure out where it is and then put it in my catch. I don't know how to go about that though. public class MySession { // private constructor private MySession() { id = new Random().Next(100000); }
// Gets the current session.
public static MySession Current
{
get
{
MySessi开发者_StackOverflow中文版on session = new MySession();
try
{
session =
(MySession)HttpContext.Current.Session["__MySession__"];
}
catch
{
//Catch nothing
}
if (session == null)
{
session = new MySession();
HttpContext.Current.Session["__MySession__"] = session;
}
return session;
}
}
// **** add your session properties here, e.g like this:
public int id { get; set; }
I feel you've got the wrong end of the stick in the way you've created your session wrapper. A session wrapper normally means you create a class which, in production code, passes all calls to the real session. In unit tests, it does not have a real session inside and could be a mock object. Your MySession class always needs a real session, so any test using will not be a true unit test.
You might not need to roll your own, there is a HttpSessionStateWrapper in System.Web.Abstractions you could try.
精彩评论