views:

105

answers:

2

I'm working on a web server application that handles requests received from mobile phones. I have request adapters which adapts requests from the phone in request classes I use in the rest of the app. What every request adapter does is that it accesses one object in a session and changes one of its properties. Now, the question: I want to write a unit test that will test this request adapter, but i don't have a session while I'm executing the test. Is there any way I can create a session or something like that to test the complete adapter?

Thanks in advance

+1  A: 

If your code that handles the request is tightly coupled to "session" than probably not.

Can you "mock" session by just passing in variables that Session might contain?

Jack Marchetti
+6  A: 

What you want to do is replace directly using a session in your adapters. You want to create an interface something like

public interface ISessionableObject
{
    MyData Data { get; set; }
}

and then create 2 implementing classes similar to

public class HttpSessionedObject : ISessionableObject
{
    public MyData Data {
        get { return Session["mydata"]; }
        set { Session["mydata"] = value; }
    }
}

public class DictionaryObject : ISessionableObject
{
    private readonly Dictionary<string, MyData> _dict = 
                                    new Dictionary<string, MyData>();

    public MyData Data {
        get { return dict ["mydata"]; }
        set { dict ["mydata"] = value; }
    }
}

Edit:

Just incase you have some confusion on what to do with this, I'm sure you have something like this:

public class Adapter
{
    public void DoSomething()
    {
         var data = Session["mydata"];
        ...
    }
}

Instead you'll want something like this

public class Adapter
{
    private readonly ISessionableObject _session;

    public Adapter(ISessionableObject session)
    {
        _session = session;
    }

    public void DoSomething()
    {
         var data = _session.Data;
        ...
    }
}

I would recommend using a Dependency Injection Framework like StructureMap to handle the creation of your objects but that's a much larger topic unrelated to this so atleast going with poor mans dependency injection your code will be similar to

public class AdapterUser
{
    public void UsingPhone()
    {
        var adapter = Adapter(new HttpSessionedObject());
        ...
    }
}

And

[UnitTest]
public class AdapterUserTest
{

    [Test]
    public void UsingPhone()
    {
        var adapter = Adapter(new DictionaryObject());
        ...
    }
}
Chris Marisic