Click here to Skip to main content
15,867,568 members
Articles / Web Development / ASP.NET
Tip/Trick

MVC Test Driven Development: Session Variables

Rate me:
Please Sign up or sign in to vote.
4.88/5 (6 votes)
12 Aug 2011CPOL2 min read 50.5K   20   9
When you write a controller which is unit testable, it would be better to avoid any dependency to the HttpContext to make things easier. If you are using any of the session variables in your controller, it will make your controller difficult to test.

Introduction

When you write a controller which is unit testable, it would be better to avoid any dependency to the HttpContext to make things easier. If you are using any of the session variables in your controller, it will make your controller difficult to test. Here, I am trying to provide a solution for this which may help you in this scenario.

Using the Code

Step 1: Write an interface, IStateProvider:

C#
public interface IStateProvider
{
    object this[string key] { get; set; }
    void Remove(string key);
}

Step 2: Write a class, SessionStateProvider implementing the IStateProvider. The SessionStateProvider will make use of the Session to store the variables.

C#
public class SessionStateProvider : IStateProvider
{
    public object this[string key]{
        get
        {
            return HttpContext.Current.Session[key];
        }
        set
        {
            HttpContext.Current.Session[key] = value;
        }
    }

    public void Remove(string key)
    {
        HttpContext.Current.Session.Remove(key);
    }
}

Step 3: Write a base class for all of your controllers, say BaseController and expose one property say, CSession in it. You can see that this property is not set initially.

C#
public class BaseController : Controller
{
    public IStateProvider CSession
    {
        get;
        set;
    }
}

Step 4: Write a custom controller factory, where we will set the State Provider as the session state provider. You can also inject here other dependencies, if any.

C#
public class MyControllerFactory:DefaultControllerFactory
{
    public override IController CreateController
    (System.Web.Routing.RequestContext requestContext, string controllerName)
    {
        IController controller;
        controller = base.CreateController(requestContext, controllerName) ;

        //Inject the Dependency.
        if (controller is BaseController)
        {
            var baseController = (BaseController)controller;
            baseController.CSession = new SessionStateProvider();

        }
        return controller;
    }
}

Step 5: Register your controller Factory in your Global.asax.cs file.

C#
void Application_Start(object sender, EventArgs e)
{
    ControllerBuilder.Current.SetControllerFactory
        (new Fadt.CMS.Web.Core.CMSControllerFactory());
    RegisterRoutes(RouteTable.Routes);
}

Step 6: Extend all your controllers from the BaseController. Now instead of using Session, you can use CSession. Since the Controller factory has injected the SessionStateProvider to the CSession property, in turn all the values you set to CSession will get stored in Session.

C#
public class MyController : BaseController
{
    public MyController()
    {
        CSession["MY_VAR"] = obj;
        CSession.Remove("MY_VAR");
    }

Testing the Controller

In the test project, write another implementation of IStateProvider. This implementation will save the variables in a dictionary rather than in Session. So by injecting the dependency through the Controller, we have decoupled the controller from the HttpContext.

C#
public class DictionaryStateProvider:IStateProvider
{
    private Dictionary<string,object> stateValueCollection =
        new Dictionary<string,object>();
    public object this[string key]
    {
        get
        {
            if (stateValueCollection.ContainsKey(key))
                return stateValueCollection[key];
            else
                return null;
        }
        set
        {
            stateValueCollection[key] = value;
        }
    }

    public void Remove(string key)
    {
        stateValueCollection.Remove(key);
    }
}

Now in the test method, write an initialization method to initialize the controller for testing.

C#
public static void InitializeController(BaseController controller)
{
    controller.CSession = new DictionaryStateProvider();
    //You can do some other injections as well here
}

[TestMethod]
public void Is_Index_Data_Loaded_Properly()
{
   MyController controller = new MyController();
   InitializeController(controller);
   controller.Index() //Call the method to test
   Assert.IsTrue(true);
}

Points of Interest

Here, we have avoided the dependency of the controllers to the HttpContext which will ease the test driven development. The whole idea is to enable the developer to develop and test the controller independent of the other dependencies.

Hope that you guys will find this helpful... please keep posting your comments. :-)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
Russell Aboobacker is a Software Engineer from India, Currently working in Cognizant, Bangalore as Software Architect. He Enjoys Coding and Sharing his Experiences with the Colleagues and Friends.When he is not coding he enjoys spending time with his Family.

If you have any suggestions / Ideas , Share it With me. arusselkm@yahoo.com

Comments and Discussions

 
QuestionAccess session in ActionFilter Pin
amit121212418-May-16 23:39
amit121212418-May-16 23:39 
QuestionFadt.CMS.Web.Core.CMSControllerFactory()? Pin
Miles Thornton19-Aug-15 5:56
Miles Thornton19-Aug-15 5:56 
QuestionGetting error for dictionary used Pin
Sandeepkumar Ramani18-Jul-13 21:22
Sandeepkumar Ramani18-Jul-13 21:22 
AnswerRe: Getting error for dictionary used Pin
Russell Aboobacker16-Aug-14 22:46
Russell Aboobacker16-Aug-14 22:46 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey6-Jul-12 23:56
professionalManoj Kumar Choubey6-Jul-12 23:56 
GeneralMy vote of 5 Pin
ThomasJWest17-Aug-11 3:32
ThomasJWest17-Aug-11 3:32 
GeneralRe: My vote of 5 Pin
Russell Aboobacker30-Jan-12 4:37
Russell Aboobacker30-Jan-12 4:37 
SuggestionGood approach Pin
abellix17-Aug-11 1:20
abellix17-Aug-11 1:20 
GeneralRe: Good approach Pin
Russell Aboobacker30-Jan-12 4:38
Russell Aboobacker30-Jan-12 4:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.