본문 바로가기

개발이야기

ASP.NET MVC Session 테스트하기

ASP.NET MVC에서 테스트 할 때 Session과 HttpContext.Current 개체는 null을 반환하므로 제대로 테스트를 할 수 없다.

HttpContext를 만드는 방법 중 제일 간단한 방법을 소개해 본다.

private void CreateHttpContext()
{
    var httpRequest = new HttpRequest("", "http://microsoft.com/", "");
    var stringWriter = new StringWriter();
    var httpResponce = new HttpResponse(stringWriter);
    var httpContext = new HttpContext(httpRequest, httpResponce);

    var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.UseCookies, SessionStateMode.InProc, false);

    httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] { typeof(HttpSessionStateContainer) }, null).Invoke(new object[] { sessionContainer });

    HttpContext.Current = httpContext;
}

테스트 시작 전 Setup에서 이와 같은 함수를 실행하면 세션 및 쿠키를 테스트 할 수가 있다.