我尝试使用以下方法测试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,但是它只有Premium和Ultimate版本,而我只为专业版提供测试的开发人员!!
使用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框架?
谢谢。
答案 0 :(得分:1)
模仿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"));
}
答案 1 :(得分:0)
你应该总是在你的应用程序中使用HttpContextBase,HttpRequestBase和HttpResponseBase作为与不可测试的具体版本相关的(没有typemock,Microsoft.Fakes或其他一些魔法)。
只需使用HttpContextWrapper类进行转换,如下所示。
var httpContextBase = new HttpContextWrapper(HttpContext.Current);
答案 2 :(得分:0)
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;
}