C#模拟Request.Browser.MajorVersion使用RhinoMocks
我有在MVC控制器以下代码:C#模拟Request.Browser.MajorVersion使用RhinoMocks
var isIe6 = Request.Browser.Type.ToUpper().Contains("IE") && Request.Browser.MajorVersion < 7;
我需要存根出使用犀牛制品的第二部分。我曾经尝试这样做:
HttpRequest.Stub(a => a.Browser).Return(new HttpBrowserCapabilitiesWrapper(new HttpBrowserCapabilities {
Capabilities = new Dictionary<string, string>
{
{"majorversion", "11"},
{"MajorVersion", "11"},
{"browser", "IE"},
{"isMobileDevice","false"}
}
}));
上面的代码在代码MajorVersion
返回0。我也试过这个:
HttpRequest.Stub(a => a.Browser.MajorVersion).Return(11);
这只是在安装时引发异常,说浏览器需要设置。我也尝试过与上面的HttpBrowserCapabilitiesWrapper
相结合,但它仍然说浏览器需要设置。
如何在MVC中存根/模拟出Request.Browser.MajorVersion?
一些测试代码,如果有人需要它:
private BasketController sut; protected HttpRequestBase HttpRequest;
[Test]
public void ShowsMajorVersionDoesNotWork()
{
// Arrange
HttpRequest.Stub(a => a.Browser).Return(new HttpBrowserCapabilitiesWrapper(new HttpBrowserCapabilities
{
Capabilities = new Dictionary<string, string>
{
{"majorversion", "11"},
{"MajorVersion", "11"},
{"browser", "IE"},
{"isMobileDevice","false"}
}
}));
//HttpRequest.Stub(a => a.Browser.MajorVersion).Return(11); // Throws Exception
sut = new BasketController()
{
Url = new UrlHelper(new RequestContext(HttpContext, new RouteData()), new RouteCollection())
};
sut.ControllerContext = new ControllerContext(HttpContext, new RouteData(), sut);
// Act
var result = sut.Method();
// Assert
Assert.That(result, Is.EqualTo("11")); // Fails, always returns 0
}
下测试方法BasketController:
public string Method() {
return Request.Browser.MajorVersion.ToString();
}
回答:
您可以创建HttpBrowserCapabilities
使用BrowserCapabilitiesFactory
(如解释here),使用IE11 user-agent string,并相似地,您可以使用正确的字符串嘲笑任何其他浏览器MajorVersion
:
public HttpRequestBase GetInterenetExplorer11StubRequest() {
return GetBrowserCapabilitiesStub("Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko");
}
public HttpRequestBase GetBrowserCapabilitiesStub(string userAgentString)
{
var browser = new HttpBrowserCapabilities
{
Capabilities = new Hashtable { { string.Empty, userAgentString } }
};
var factory = new BrowserCapabilitiesFactory();
factory.ConfigureBrowserCapabilities(new NameValueCollection(), browser);
var request = MockRepository.GenerateStub<HttpRequestBase>();
request.Stub(a => a.Browser).Return(new HttpBrowserCapabilitiesWrapper(browser));
return request;
}
以上是 C#模拟Request.Browser.MajorVersion使用RhinoMocks 的全部内容, 来源链接: utcz.com/qa/261521.html