.NET如何捏造HttpContext对象

对于unit testing,我试图向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始终为零。 价值观没有得到

我究竟做错了什么?

根据您要定位的.NET版本,您可能需要查看HttpContextBase和HttpContextWrapper 。 HttpContextBase是抽象的,因此像moq这样的模拟框架将允许您无论如何选择它的属性。