使用Rhino Mocks测试ASP.NET MVC中的出站URL生成

时间:2010-11-11 14:45:26

标签: asp.net-mvc mocking rhino-mocks

我很难找到一个完整的示例,说明如何使用Rhino Mocks测试出站网址所需的请求上下文。

我有一个使用Moq的例子,我试图转换为Rhino Mocks,但我没有太多运气。

    private static HttpContextBase MakeMockHttpContext(string url)
    {
        var mocks = new MockRepository();
        var mockHttpContext = mocks.StrictMock<HttpContextBase>();
        // Mock the request
        var mockRequest = mocks.StrictMock<HttpRequestBase>();
        mockHttpContext.Expect(x => x.Request).Return(mockRequest);
        mockRequest.Expect(x => x.AppRelativeCurrentExecutionFilePath).Return(url);
        // Mock the response
        var mockResponse = mocks.StrictMock<HttpResponseBase>();
        mockHttpContext.Expect(x => x.Response).Return(mockResponse);
        mockResponse.Stub(r => r.ApplyAppPathModifier(Arg<string>.Is.Anything))
            .Do(new Func<string, string>(s => s));

        return mockHttpContext;
    }

    private string GenerateUrl(object values)
    {
        RouteCollection routeConfig = new RouteCollection();
        Global.RegisterRoutes(routeConfig);
        var mockContext = MakeMockHttpContext(null);
        var requestContext = new RequestContext(mockContext, new RouteData());

        return UrlHelper.GenerateUrl(null, null, null, 
            new RouteValueDictionary(values), routeConfig, requestContext, true);
    }

    [Test]
    public void Catalog_index_returns_root_url()
    {
        GenerateUrl(new { controller = "Catalog", action = "Index" }).ShouldEqual("/");
    }

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)