2012-07-17 49 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"} 
                   } 
                 };