SORU
8 Mart 2012, PERŞEMBE


HttpContext Ayarı.Mevcut.Bir birim test oturumu

Birim test için çalışıyorum bir web hizmeti var. Servisin bu kadar gibi: HttpContext çeşitli değerlere çeker

 m_password = (string)HttpContext.Current.Session["CustomerId"];
 m_userID = (string)HttpContext.Current.Session["CustomerUrl"];

birim testi kapsamında çalışan basit bir istek gibi kullanarak yaratıyorum:

SimpleWorkerRequest request = new SimpleWorkerRequest("", "", "", null, new StringWriter());
HttpContext context = new HttpContext(request);
HttpContext.Current = context;

HttpContext değerlerini ayarlamak için çalışıyorum ancak, her ne zaman.Mevcut.Oturum

HttpContext.Current.Session["CustomerId"] = "customer1";
HttpContext.Current.Session["CustomerUrl"] = "customer1Url";

HttpContext yazan null başvuru özel durumu anlıyorum.Mevcut.Oturum null. Birim test içinde geçerli oturumu başlatmak için herhangi bir yolu var mı?

CEVAP
12 NİSAN 2012, PERŞEMBE


"Sahte" bu gibi: yeni bir httpcontext oluşturarak

http://www.necronet.org/archive/2010/07/28/unit-testing-code-that-uses-httpcontext-current-session.aspx

Bu kodu aldı ve statik yardımcı bir sınıf gibi koydum:

public static HttpContext FakeHttpContext()
{
    var httpRequest = new HttpRequest("", "http://stackoverflow/", "");
    var stringWriter = new StringWriter();
    var httpResponse = new HttpResponse(stringWriter);
    var httpContext = new HttpContext(httpRequest, httpResponse);

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

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

    return httpContext;
}

ya da kullanmak HttpSessionState yeni bir örneğini oluşturmak için yansıma yerine, sadece HttpContext (Brent M. Büyü yorum başına) HttpSessionStateContainer ekleyebilirsiniz:

SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer);

ve sonra birim testleri de öyle diyebilirsiniz:

HttpContext.Current = MockHelper.FakeHttpContext();

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Joshua Benedict

    Joshua Bened

    26 EKİM 2013
  • Ludique

    Ludique

    21 NİSAN 2009
  • ODN

    ODN

    26 Kasım 2006