使用最小起订量和会话状态包装器进行测试
我正在使用如下所示的会话包装器。我遇到的问题是,当运行测试时,尝试不起作用,它会进入捕获状态,因此会话变量永远不会被设置。我正在使用 Moq 为我的模拟上下文创建模拟会话状态。如果我创建一个像这样的变量:
Session["variable"] = "something";
那就可以正常工作并持续到测试结束。在我的包装中创建的所有内容都没有。由于会话以某种方式持续存在,我的理论是我需要弄清楚它在哪里,然后将其放入我的捕获中。但我不知道该怎么做。 公共课我的会话 { // 私有构造函数 私人我的会话() { id = new Random().Next(100000); }
// Gets the current session.
public static MySession Current
{
get
{
MySession 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'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
{
MySession 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; }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我觉得您创建会话包装器的方式是错误的。会话包装器通常意味着您创建一个类,该类在生产代码中将所有调用传递给真实会话。在单元测试中,它内部没有真正的会话,可能是一个模拟对象。您的 MySession 类始终需要一个真正的会话,因此任何使用的测试都不会是真正的单元测试。
您可能不需要自己动手,System.Web.Abstractions 中有一个 HttpSessionStateWrapper 您可以尝试。
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.