기본적으로 두 가지 방법이 있습니다.
.NET 3.5 이상을 사용한다고 가정합니다. HttpSessionStateBase 객체를 생성자 매개 변수로 사용하도록 구현을 변경하면이 구현을 조롱 할 수 있습니다. 온라인 수행 방법에 대한 온라인 자습서가 몇 가지 있습니다. 테스트 솔기를 작성하는 것입니다
public class MyObjectThatUsesSession
{
HttpSessionStateBase _session;
public MyObjectThatUsesSession(HttpSessionStateBase sesssion)
{
_session = session ?? new HttpSessionStateWrapper(HttpContext.Current.Session);
}
public MyObjectThatUsesSession() : this(null)
{}
}
또는, 아마 조금 더 유연 디자인 : 그런 다음 응용 프로그램을 시작할 때이 철사 나 같은 (가난한 사람의 의존성 주입)를 수행하는 IoC 컨테이너를 사용할 수 있습니다 다른 객체의 세션과의 상호 작용을 래핑하면됩니다. 나중에이를 데이터베이스, 쿠키 또는 캐시 기반 구현으로 변경할 수 있습니다. 당신은 다음 시험을위한 모의 IStateStorage 구현을 만들 MOQ를 사용하거나 간단한 사전을 기반 구현을 만들 수 있습니다
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;
}
}
:처럼 뭔가.
희망이 있습니다.
나는 가난한 남자 DI 유추를 좋아했다. :) – theusguy