【发布时间】:2018-04-30 08:46:28
【问题描述】:
我正在尝试为相当基本的控制器操作编写一些单元测试,其中我设置了 Session["User"]。当我运行测试时,此时它失败并出现空引用异常。不完全确定如何解决这个问题。
控制器:
public ActionResult Index(int id)
{
Session["User"] = Id;
if (Id != 0)
{
return RedirectToAction("Home", "Home", new { Id});
}
return RedirectToAction("Register", "Home", new { Id});
}
测试:
[TestMethod]
public void NewUser_ShouldGoToRegister()
{
var controller = new HomeController();
HttpContext.Current = FakeHttpContext();
HttpContext.Current.Session.Add("User", "0");
var result = controller.Index(0) as ViewResult;
Assert.AreEqual("Register", result.ViewName);
}
public HttpContext FakeHttpContext()
{
var httpRequest = new HttpRequest("", "http://localhost/", "");
var httpResponce = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(httpRequest, httpResponce);
var sessionContainer =
new HttpSessionStateContainer("id",
new SessionStateItemCollection(),
new HttpStaticObjectsCollection(),
10,
true,
HttpCookieMode.AutoDetect,
SessionStateMode.InProc,
false);
httpContext.Items["AspSession"] =
typeof(HttpSessionState)
.GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
CallingConventions.Standard,
new[] { typeof(HttpSessionStateContainer) },
null)
.Invoke(new object[] { sessionContainer });
HttpContext.Current = httpContext;
}
【问题讨论】:
-
您需要阅读有关模拟 Web 对象(例如 HttpContext、HttpRequest 等)的内容。基本上从一开始就阅读有关单元测试控制器代码的内容。
-
我有一个 [TestInitialize] 方法可以设置类似的东西
-
我们怎么知道你做了那件事以及你在那里犯了什么错误?请分享代码。
-
非常抱歉。我更新了代码以包含它。原本打算这样做
标签: c# asp.net-mvc unit-testing session httpcontext