Click here to Skip to main content
13,141,747 members (57,259 online)
Click here to Skip to main content
Articles » Web Development » ASP.NET » General » Revisions
Add your own
alternative version


20 bookmarked
Posted 12 Aug 2011

MVC Test Driven Developement: Session Variables

, 12 Aug 2011
Rate this:
Please Sign up or sign in to vote.
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.
This is an old version of the currently published article.


When you write a controller which is unit testable, it would be better to avoid any dependency to the HttpContext to make the 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:

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.

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

    public void Remove(string 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.

public class BaseController : Controller
    public IStateProvider CSession

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.

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.

void Application_Start(object sender, EventArgs e)
    	(new Fadt.CMS.Web.Core.CMSControllerFactory());

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.

public class MyController : BaseController
    public MyController()
        CSession["MY_VAR"] = obj;

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.

public class DictionaryStateProvider:IStateProvider
    private Dictionary<string> stateValueCollection =
        new Dictionary<string>();
    public object this[string key]
            if (stateValueCollection.ContainsKey(key))
                return stateValueCollection[key];
                return null;
            stateValueCollection[key] = value;

    public void Remove(string key)

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

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

public void Is_Index_Data_Loaded_Properly()
   MyController controller = new MyController();
   controller.Index() //Call the method to test

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 th 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 :-)


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


About the Author

Russell Aboobacker
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.

You may also be interested in...


Comments and Discussions

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.
QuestionAccess session in ActionFilter Pin
amit121212418-May-16 23:39
memberamit121212418-May-16 23:39 
QuestionFadt.CMS.Web.Core.CMSControllerFactory()? Pin
Miles Thornton19-Aug-15 5:56
memberMiles Thornton19-Aug-15 5:56 
QuestionGetting error for dictionary used Pin
Sandeep Ramani18-Jul-13 21:22
memberSandeep Ramani18-Jul-13 21:22 
AnswerRe: Getting error for dictionary used Pin
Russell Aboobacker16-Aug-14 22:46
memberRussell Aboobacker16-Aug-14 22:46 
GeneralMy vote of 5 Pin
manoj kumar choubey6-Jul-12 23:56
membermanoj kumar choubey6-Jul-12 23:56 
GeneralMy vote of 5 Pin
ThomasJWest17-Aug-11 3:32
memberThomasJWest17-Aug-11 3:32 
GeneralRe: My vote of 5 Pin
Russell Aboobacker30-Jan-12 4:37
memberRussell Aboobacker30-Jan-12 4:37 
SuggestionGood approach Pin
abellix17-Aug-11 1:20
memberabellix17-Aug-11 1:20 
GeneralRe: Good approach Pin
Russell Aboobacker30-Jan-12 4:38
memberRussell 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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170915.1 | Last Updated 12 Aug 2011
Article Copyright 2011 by Russell Aboobacker
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid