Mocking HttpSessionState in ASP.net for nunit testing

Gilbert Liddell picture Gilbert Liddell · Mar 28, 2011 · Viewed 8.3k times · Source

I've see n a lot of discussions surrounding HttpSessionState and asp.net MVC. I'm trying to write tests for an asp.net application and wondering if it's possible to mock the HttpSessionState and if so, how?

I'm currently using Rhino Mocks and Nunit

Answer

MikeSullivan picture MikeSullivan · Jul 9, 2011

Gilbert,

Maybe I'm too late for you. I'm using MSpec, but I think the concepts are similar. I needed to mock several components of the HttpContext in the controllers under test.

I started with these following classes to mock up the necessary (for my purposes) components in the HttpContextBase. I overrode only the necessary pieces inside the classes. Your needs will vary as to the mocks you need in the controller. It's fairly easy to add mocks as needed once you understand the pattern.

public class MockHttpContext : HttpContextBase 
{

    private readonly HttpRequestBase _request = new MockHttpRequest();
    private readonly HttpServerUtilityBase _server = new MockHttpServerUtilityBase();
    private HttpSessionStateBase _session = new MockHttpSession();

    public override HttpRequestBase Request
    {
        get { return _request; }
    }
    public override HttpServerUtilityBase Server
    {
        get { return _server; }
    }
    public override HttpSessionStateBase Session
    {
        get { return _session; }
    }
}

public class MockHttpRequest : HttpRequestBase
{
    private Uri _url = new Uri("http://www.mockrequest.moc/Controller/Action");

    public override Uri Url
    {
        get { return _url; }
    }
}

public class MockHttpServerUtilityBase : HttpServerUtilityBase
{
    public override string UrlEncode(string s)
    {
        //return base.UrlEncode(s);     
        return s;       // Not doing anything (this is just a Mock)
    }
}


public class MockHttpSession : HttpSessionStateBase
{
    // Started with sample http://stackoverflow.com/questions/524457/how-do-you-mock-the-session-object-collection-using-moq
    // from http://stackoverflow.com/users/81730/ronnblack

    System.Collections.Generic.Dictionary<string, object> _sessionStorage = new   System.Collections.Generic.Dictionary<string,object>();
    public override object this[string name]
    {
        get { return _sessionStorage[name]; }
        set { _sessionStorage[name] = value; }
    }

    public override void Add(string name, object value)
    {
        _sessionStorage[name] = value;
    }
}

Here is how I setup the Controller Context to use the mocks (MSpec). This is setup for the actual tests on the contoller (the tests derive from this class)

public abstract class BlahBlahControllerContext
{
    protected static BlahBlahController controller;

    Establish context = () =>
    {
        controller = new BlahBlahController();
        controller.ControllerContext = new ControllerContext()
        {
            Controller = controller,
            RequestContext = new RequestContext(new MockHttpContext(), new RouteData()),
        };
    };
}

To further illustrate here is a test (Specification in MSpec world) that uses the mock session:

[Subject("ACCOUNT: Retrieve Password")]
public class retrieve_password_displays_retrieve_password2_page_on_success : BlahBlahControllerContext
{
    static ActionResult result;
    static RetrievePasswordModel model;

    Establish context = () =>
    {
        model = new RetrievePasswordModel()
        {
            UserName = "Mike"
        };
    };

    Because of = () =>
    {
        result = controller.RetrievePassword(model);
    };

    It should_return_a_RedirectToRouteResult = () => 
    { 
        result.is_a_redirect_to_route_and().action_name().ShouldEqual("RetrievePassword2"); 
    };

    It session_should_contain_UN_value = () =>
    {
        controller.HttpContext.Session["UN"].ShouldEqual("Mike");
    };

    It session_should_contain_PQ_value = () =>
    {
        controller.HttpContext.Session["PQ"].ShouldEqual("Question");
    };
}

I realize this doesn't use Rhino Mocks. I hope it illustrates the principles and readers can adopt it to their specific tools and methods.