代码改变世界

测试包含HttpContext.Current的代码

  敏捷的水  阅读(667)  评论(1编辑  收藏  举报

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[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);
}
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示