I am trying to write some unit tests for fairly basic controller actions, in which I set Session["User"]. When I run the test, it is failing at this point with a null reference exception. Not entirely sure how to get round this.
Controller:
public ActionResult Index(int id)
{
Session["User"] = Id;
if (Id != 0)
{
return RedirectToAction("Home", "Home", new { Id});
}
return RedirectToAction("Register", "Home", new { Id});
}
Test:
[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;
}