C# 模拟 Request.Browser.MajorVersion 使用 RhinoMocks

C# Mock Request.Browser.MajorVersion using RhinoMocks

我在 MVC 控制器中有以下代码:

        var isIe6 = Request.Browser.Type.ToUpper().Contains("IE") && Request.Browser.MajorVersion < 7;

我需要使用 Rhino Mocks 删除第二部分。我试过这个:

HttpRequest.Stub(a => a.Browser).Return(new HttpBrowserCapabilitiesWrapper(new HttpBrowserCapabilities
        {
            Capabilities = new Dictionary<string, string>
            {
                {"majorversion", "11"},
                {"MajorVersion", "11"},
                {"browser", "IE"},
                {"isMobileDevice","false"}
            }
        }));

上面的代码returns0为MajorVersion中的代码。我也试过这个:

HttpRequest.Stub(a => a.Browser.MajorVersion).Return(11);

这只是在设置时引发异常,提示需要设置浏览器。我也试过结合上面的HttpBrowserCapabilitiesWrapper,但它仍然说需要设置浏览器。

如何在 MVC 中 stub/mock 输出 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();
    }

您可以使用 BrowserCapabilitiesFactory 创建 HttpBrowserCapabilities(如 here), using the 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;
}