我測試的MVC 3控制器調用這個類中的方法:嘲諷HttpContext.Current使用上NUnit測試MOQ
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's Blog的建議是:
[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!
這是異常消息被thr自己當HttpContext.Current == null
我只需要Session對象'存在',而不是存儲在會話上的實際值。
你能告訴我什麼我做錯了嗎?
謝謝。
這是我最後做的,不知何故,感覺就像一個解決辦法......但後來我發現其他人做同樣的方式和您的評論這裏經過:解決方法感覺幾乎消失:) – qbantek