开发者

C#: Unit testing classes of web application

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 开发者_如何学Cproperties. 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


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());
        ...
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜