Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Test Controller Session Variables in MVC3

I am unit testing my controller.

In one of my controller methods I am setting Session variables:

 public void Index(){
      Session["foo"] = "bar";

      return View();
 }

How can I unit test this? The problem is that the Session property is null when testing. Injecting is not possible because the Session property is readonly.

 [TestMethod]
 public void TestIndex()
     // When
     _controller.Index();

     // Then
     Assert.AreEqual("bar", _controller.Session["foo"])
like image 264
Tobias Avatar asked Dec 17 '22 11:12

Tobias


2 Answers

Personally I like using the MvcContrib TestHelper which mocks all the HTTP pipeline:

[TestMethod]
public void HomeController_Index_Action_Should_Store_Bar_In_Session()
{
    // arrange
    var sut = new HomeController();
    new TestControllerBuilder().InitializeController(sut);

    // act
    sut.Index();

    // assert
    Assert.AreEqual("bar", (string)sut.Session["foo"]);
}
like image 91
Darin Dimitrov Avatar answered Jan 03 '23 15:01

Darin Dimitrov


This is what I used for Unit Test friendly Session Caching. By checking HttpContext.Current for null, you're by passing the caching for nunit tests and still allow your program to function normally.

This is the simplest solution without making a lot of code changes in your project.

internal class SessionCache
{
    public static void Store(string key, object val) {
        if (HttpContext.Current != null) {
            HttpContext.Current.Session[key] = val;
        }
    }

    public static object Retrieve(string key) {
        if (HttpContext.Current != null) {
            return HttpContext.Current.Session[key];
        }

        return null;
    }
}
like image 44
Ra Truong Avatar answered Jan 03 '23 15:01

Ra Truong