虽说直接测试这样的代码有违设计的原则,但用下面的方法可以对已有这样的代码进行单元测试
[TestMethod] public void Test_CreateHttpSessionTest() { HttpContext.Current = new HttpContext(new HttpRequest(string.Empty,"http://localhost/",string.Empty), new HttpResponse(new StringWriter())); SessionStateItemCollection sessions = new SessionStateItemCollection(); sessions["PartnerAlias"] = "devtest1"; IHttpSessionState iSessState = new HttpSessionStateContainer (string.Empty,sessions, new HttpStaticObjectsCollection(),20000,true, HttpCookieMode.UseCookies,SessionStateMode.Off,false); SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current,iSessState); Assert.IsNotNull(HttpContext.Current.Session); Assert.AreEqual(HttpContext.Current.Session["partnerAlias"].ToString(), "devtest1"); Assert.IsNotNull(HttpContext.Current.Cache); }