.NET如何捏造HttpContext对象

时间:2010-11-18 12:39:15

标签: c# .net vb.net

用于单元测试我试图向HttpApplicationState对象添加一个值,该对象是HttpContext.Current类的Application属性。我尝试使用以下代码

        TextWriter tw = new StringWriter();
        HttpWorkerRequest wr = new SimpleWorkerRequest("/webapp", @"path...", "logon.asp", "", tw);

        HttpContext.Current = new HttpContext(wr);

        //I try the following 2 lines
        HttpContext.Current.Application["KeyValue"] = "myValue";
        HttpContext.Current.Application.Add("KeyValue", "myValue");

        var count = HttpContext.Current.Application.Count;
        var get1 = HttpContext.Current.Application["KeyValue"];
        var get2 = HttpContext.Current.Application.Get("KeyValue");

但是HttpContext.Current.Application.Count始终为零。值不会得到

我做错了什么?

1 个答案:

答案 0 :(得分:0)

根据您定位的.NET版本,您可能需要查看HttpContextBaseHttpContextWrapper。 HttpContextBase是抽象的,因此像moq这样的模拟框架将允许您随意分配其属性。