我最近实现了一个工作单元模式,作为一个环境,我们正在使用更多的单元测试。目前,该实现写入了一个写入 session 的 session 助手。我如何对 session 的这些方面进行单元测试?我应该制作一个存储库模式吗? (具有具体 session 实现和具体模拟实现的存储库接口(interface))这通常是如何完成的?
我知道可能有不止一种方法可以解决这个问题,但我只是在寻找一些建议。
最佳答案
基本上有两种方法可以做到这一点。
假设您使用的是 .NET 3.5 或更高版本。更改您的实现以将 HttpSessionStateBase 对象作为构造函数参数,然后您可以模拟此实现 - 在线有一些教程介绍如何执行此操作。然后,您可以使用 IoC 容器在应用程序启动时将其连接起来或执行类似操作(可怜的依赖注入(inject)):
public class MyObjectThatUsesSession
{
HttpSessionStateBase _session;
public MyObjectThatUsesSession(HttpSessionStateBase sesssion)
{
_session = session ?? new HttpSessionStateWrapper(HttpContext.Current.Session);
}
public MyObjectThatUsesSession() : this(null)
{}
}
或者,可能更好和更灵活的设计是通过将您与 session 的交互包装在另一个对象中来创建测试接缝。然后您可以稍后将其更改为基于数据库、cookie 或缓存的实现。像这样的东西:
public class MyObjectThatUsesSession
{
IStateStorage _storage;
public MyObjectThatUsesSession(IStateStorage storage)
{
_storage= storage ?? new SessionStorage();
}
public MyObjectThatUsesSession() : this(null)
{}
public void DoSomethingWithSession()
{
var something = _storage.Get("MySessionKey");
Console.WriteLine("Got " + something);
}
}
public interface IStateStorage
{
string Get(string key);
void Set(string key, string data);
}
public class SessionStorage : IStateStorage
{
//TODO: refactor to inject HttpSessionStateBase rather than using HttpContext.
public string Get(string key)
{
return HttpContext.Current.Session[key];
}
public string Set(string key, string data)
{
HttpContext.Current.Session[key] = data;
}
}
然后您可以使用 Moq 为您的测试创建一个模拟的 IStateStorage 实现,或者创建一个简单的基于字典的实现。
希望对您有所帮助。
关于c# - 单元测试 - session 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6548572/