我有在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();
}
請向我們展示[mcve](即顯示問題的最簡單的單元測試)。 – mjwills