2011-02-17 56 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的依賴,並使測試更容易。