我正在测试一个调用此类方法的MVC 3控制器:
public class SessionVar
{
/// <summary>
/// Gets the session.
/// </summary>
private static HttpSessionState Session
{
get
{
if (HttpContext.Current == null)
throw new ApplicationException
("No Http Context, No Session to Get!");
return HttpContext.Current.Session;
}
}
public static T Get<T>(string key)
{
return Session[key] == null ? default(T) : (T)Session[key];
}
...
}
我遵循Hanselman的博客的建议,我的测试方法如下:
[Test]
public void CanRenderEmployeeList()
{
_mockIEmployeeService.Setup(s => s.GetEmployees(StatusFilter.OnlyActive))
.Returns(BuildsEmployeeList().Where(e => e.IsApproved));
var httpContext = FakeHttpContext();
var target = _employeeController;
target.ControllerContext = new ControllerContext
(new RequestContext(httpContext, new RouteData()), target);
var result = target.Index();
Assert.IsNotNull(result);
Assert.IsInstanceOf<ViewResult>(result);
var viewModel = target.ViewData.Model;
Assert.IsInstanceOf<EmployeeListViewModel>(viewModel);
}
public static HttpContextBase FakeHttpContext()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();
context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
context.Setup(ctx => ctx.Session).Returns(session.Object);
context.Setup(ctx => ctx.Server).Returns(server.Object);
return context.Object;
}
但是我的测试一直失败,我得到了以下结果:
CanRenderEmployeeListSystem.ApplicationException : No Http Context,
No Session to Get!
当HttpContext.Current == null
时需要抛出的异常信息是什么?
我只需要“存在”Session对象,而不需要Session中实际存储的值。
你能告诉我哪里做错了吗?
谢谢。