2012-07-17 47 views
1

我正在寫單元測試,其中我需要一個假的HttpContext。我使用了Phil Haack的HttpSimulator(http://haacked.com/archive/2007/06/19/unit-tests-web-code-without-a-web-server-using-httpsimulator.aspx)。 但在Sitecore的API函數的拋出一個異常,在下面的代碼:模擬用戶代理

request.Browser.Browser.IndexOf("IE", StringComparison.OrdinalIgnoreCase) > -1; 

我調試我的代碼和request.Browser.Browser是空的。我試圖用Moq填補財產,但我得到一個例外。我也嘗試將其添加爲標題。

我的代碼如下所示:

using (HttpSimulator simulator = new HttpSimulator("/", "localpath")) 
{ 
    //NameValueCollection nvc = new NameValueCollection { { "User-Agent", "IE" } }; 
    //simulator.SimulateRequest(new Uri("http://www.foo.bar"), HttpVerb.GET, nvc); 
    simulator.SimulateRequest();   

    var browserMock = new Mock<HttpBrowserCapabilities>(); 
    browserMock.SetupAllProperties(); 
    //browserMock.SetupProperty(b => b.Browser, "IE"); 
    HttpContext.Current.Request.Browser = browserMock.Object; 
} 

有誰知道我可以嘲笑這個屬性?

+0

http://hadihariri.com/2009/03/ 31 /嘲笑-用戶代理屬性-在-ASP淨MVC與 - MOQ / – 2012-12-05 22:06:50

回答

1

這不能完成,你將不得不使用HttpContextBase e.d. MVC中的類。與Web窗體原來的單元測試是凌亂

4

其實這是可能的 - 你可以直接在請求設置的瀏覽器屬性(?):

httpSim.SimulateRequest(new Uri("http://www.test.com")); 

HttpContext.Current.Request.Browser = new HttpBrowserCapabilities 
                 { 
                  Capabilities = new Dictionary<string,string> 
                   { 
                    {"majorversion", "8"}, 
                    {"browser", "IE"}, 
                    {"isMobileDevice","false"} 
                   } 
                 };