在HtmlHelper扩展方法中模拟出HttpContext

时间:2012-11-19 12:51:02

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 moq rhino-mocks

如何在此扩展方法中模拟HttpContext

public static class MyHtmlHelper
{
    public static string GetFullPath(this HtmlHelper helper)
    {
        var url = HttpContext.Current.Request.Url;

        return url.Scheme + "://" + url.AbsolutePath;
    }
}

1 个答案:

答案 0 :(得分:2)

创建一个HttpContextFactory,使用它然后在测试中设置它。

public static class HttpContextFactory
    {
        [ThreadStatic]
        private static HttpContextBase _mockHttpContext;

        public static void SetHttpContext(HttpContextBase httpContextBase)
        {
            _mockHttpContext = httpContextBase;
        }

        public static HttpContextBase GetHttpContext()
        {
            if (_mockHttpContext != null)
            {
                return _mockHttpContext;
            }

            if (HttpContext.Current != null)
            {
                return new HttpContextWrapper(HttpContext.Current);
            }
            return null;
        }
    }

然后在你的代码中:

var url = HttpContextFactory.GetHttpContext().Request.Url;

然后在您的测试中使用该属性作为接缝

HttpContextFactory.SetHttpContext(HttpMocks.HttpContext());

其中HttpMocks具有以下内容并将根据您的测试进行调整:

public static HttpContextBase HttpContext()
      {
          var context = MockRepository.GenerateMock<HttpContextBase>();
          context.Stub(r => r.Request).Return(HttpRequest());
          // and stub out whatever else you need to, like session etc
          return context;
      }


      public static HttpRequestBase HttpRequest()
      {
          var httpRequest = MockRepository.GenerateMock<HttpRequestBase>();
          httpRequest.Stub(r => r.Url).Return("/"); //or some test setting
          return httpRequest;
      }