Testing a class using HttpContext.Current.Session in ASP.NET MVC

I am adding some tests to a class that uses HttpContext.Current.Session inside, and we are porting to ASP.NET MVC. My class is as follows:

class Foo
{
    public void foo()
    {
        HttpContext.Current.Session["foo"] = "foo";
    }
}

I decided to change it like this:

class Foo
{
    IHttpSessionState session;

    public Foo() : this(HttpContext.Current.Session) {}

    public Foo(IHttpSessionState session)
    {
        m_session = session;
    }

    public void foo()
    {
        m_session["foo"] = "foo";
    }
}

The problem is the default constructor. I cannot pass old classes, because they do not implement the new ASP.NET MVC interfaces.

Anyway, to get instances that implement IHttpSessionState in the default constructor?

thanks

+5
source share
1 answer

Try this, he used the IHttpSessionState wrapper that MVC uses.

class Foo
{
    // member variable set by constructor
    IHttpSessionState m_session;

    // if no session is passed it attempts to create a new session state wrapper from the current session
    public Foo() : this(new HttpSessionStateWrapper(HttpContext.Current.Session)) {}

    public Foo(IHttpSessionState session)
    {
        m_session = session;
    }

    public void foo()
    {
        m_session["foo"] = "foo";
    }
}
+5
source

All Articles