我的控制器中有一个操作可以验证我的 Session 是否已过期(== null),如果是,则重定向到我的登录名。我想为此添加一个单元测试,但我不能将 Session 设置为 null 或模拟它。任何人都知道我该怎么做以及测试它是否是个好主意?
这是我的控制器操作:
private InvestigationStep2Model _step2Model
{
get
{
if (Session == null) return null;
if (Session["investigationStep2"] == null) Session["investigationStep2"] = new InvestigationStep2Model();
return (InvestigationStep2Model) Session["investigationStep2"];
}
set { Session["investigationStep2"] = value; }
}
public virtual ActionResult Step2()
{
if (_step2Model == null) return RedirectToAction(MVC.Session.Logout());
ViewData.Model = _step2Model;
return View();
}
以及我所有尝试模拟 Session 的测试
[Test]
public void Step2_RedirectToActionWhenNoSession()
{
_builder.InitializeController(_controller);
Expect.Call(_controller.Session).Repeat.Any().Return(null);
//_controller.HttpContext.Session.Abandon();//.SetSessionStateBehavior(SessionStateBehavior.Disabled); // .Session..Abandon());// .Stub(b => b.Session).Return(null);
_mock.ReplayAll();
var result = _controller.Step2();
_mock.VerifyAll();
result.AssertActionRedirect().ToAction<SessionController>(c => c.Logout());
}
但没有任何工作...
谢谢!