Search code examples
c#asp.net-mvcunit-testingmockinghttpcontext

Mocking HttpContext (Session)



I've read many articles and blogs about mocking in mvc... Many of them were helpful, but i still have some problems:

  • One such issue is that I need to use Session in My ActionResult, but in my Tests i get a NullReferenceException when Session is accessed.

    public ActionResult Index()
    {
      if (Session["Something"] == null)
      {
        Session.Add("Something", <smth>);
      }
      else
      {
        Session["Something"] = <smth>;
      }
      return redirect to action("Index2");
    }
    
  • My test look like this:

    HomeController controller = new HomeController;
    var result = controller.Index() as ViewResult;
    Assert.AreEqual("Index2", result.ViewName);
    

Solution

  • You can use tools such as the MVC-contrib TestHelper

    This sample from the site shows how to test an action that stores a posted form value in the session

    [Test]
    public void AddSessionStarShouldSaveFormToSession()
    {
        TestControllerBuilder builder = new TestControllerBuilder();
        StarsController controller = new StarsController();
        builder.InitializeController(controller);
    
        //note that this is assigned before the controller action. This simulates the server  filling out the form data from the request
        builder.Form["NewStarName"] = "alpha c";
    
        //this assumes that AddSessionStar takes the form data and adds it to the session
        controller.AddSessionStar();
    
        Assert.AreEqual("alpha c", controller.HttpContext.Session["NewStarName"]);
    }