嘲笑 HttpContext.Current.Application

Mocking HttpContext.Current.Application

我尝试测试 Mock HttpContext.Current.Application 第三个库,它使用以下方法:

HttpContext.Current.Application.Add ( "key","value");
HttpContext.Current.Application.Get ("key");

我测试了很多模拟框架 Moq、RhinoMock、FakeSystemWeb、FakeHttpContext 但是在Application Dictionary里面是不可能加值的,总是HttpContext.Current.Application.Count == 0

唯一可行的解​​决方案是 Microsoft.Fakes,但遗憾的是,它仅适用于高级版和终极版,而我向其提供测试的开发人员仅提供专业版!!

使用 Microsoft.Fakes(有效):

 public MockHttpContext()
 {
      //MOCK System.Web
      _shimsContext = ShimsContext.Create();
      var httpRequest = new HttpRequest("", "http://www.monsite.com", "");
      var httpContext = new HttpContext(httpRequest, new(HttpResponse(new(StringWriter()));
      var applicationState = httpContext.Application;
      System.Web.Fakes.ShimHttpContext.CurrentGet = () => httpContext;
      System.Web.Fakes.ShimHttpContext.AllInstances.ApplicationGet = context => applicationState;
   }

您有想法或如何分发我的测试 Microsoft.Fakes 或其他 Mocking 框架吗?

谢谢。

您应该始终在您的应用程序中使用 HttpContextBase、HttpRequestBase 和 HttpResponseBase,而不是无法测试的具体版本(没有 typemock、Microsoft.Fakes 或其他魔法)。

只需使用 HttpContextWrapper class 进行转换,如下所示。

var httpContextBase = new HttpContextWrapper(HttpContext.Current);

Prig 可以吗。您可以编写代码来模拟 HttpContext,如下所示:

public MockHttpContext()
{
    //MOCK System.Web
    _indirectionsContext = new IndirectionsContext();
    var httpRequest = new HttpRequest("", "http://www.monsite.com", "");
    var httpContext = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
    var applicationState = httpContext.Application;
    System.Web.Prig.PHttpContext.CurrentGet().Body = () => httpContext;
    System.Web.Prig.PHttpContext.ApplicationGet().Body = context => applicationState;
}

模拟 HttpContext 的绝佳框架是 Typemock Isolator。 您可以按照下面的示例进行操作:

 [TestMethod, Isolated]
 public void TestMethod1()
 {
     var httpRequest = new HttpRequest("", "http://www.monsite.com", "");
     var httpContext = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
     var httpApp = httpContext.Application;

     Isolate.Fake.AllInstances<HttpContext>();

     Isolate.WhenCalled(() => HttpContext.Current).WillReturn(httpContext);
     Isolate.WhenCalled(() => HttpContext.Current.Application).WillReturn(httpApp);

     HttpContext.Current.Application.Add("key1", "value1");
     HttpContext.Current.Application.Add("key2", "value2");
     HttpContext.Current.Application.Add("key3", "value3");

     Assert.AreEqual(3, HttpContext.Current.Application.Count);
     Assert.AreEqual("value1", HttpContext.Current.Application.Get("key1"));
}