代码改变世界

测试包含HttpContext.Current的代码

2009-09-18 11:24  敏捷的水  阅读(664)  评论(1编辑  收藏  举报

虽说直接测试这样的代码有违设计的原则,但用下面的方法可以对已有这样的代码进行单元测试

[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);
}