2011-02-17 110 views
3

我可以在我的单元测试方法中访问HttpRuntime。当我每次尝试访问时都显示HttpRuntime在当前上下文中不存在。在我的目标方法,我想测试访问缓存变量VisualStudio中的HttpRuntime UnitTest


    HttpRuntime.Cache[key]; 

这可能吗?还是我在这里错过了什么?

感谢

回答

1

您可以使用SimpleWorkerRequest对象在您的单元测试中创建一个HttpContext。

 
TextWriter writer = new StringWriter(); 
HttpWorkerRequest httpRequest = new SimpleWorkerRequest("virtualDir", "physicalDir", "page", "", writer); 
HttpContext.Current = new HttpContext(httpRequest); 
HttpContext.Current.Cache[key] = some value.. 
1

你最好的选择将是重构你的目标的方法不能直接访问的httpRuntime,而是将这些信息作为参数传递或有它跟一个包装的httpRuntime的接口。这样你就可以打破对HttpRuntime的依赖,并使测试更容易。