参见英文答案 >
How do I mock the HttpContext in ASP.NET MVC using Moq?5个
我需要一个HttpContext的模拟单元测试.但我正在努力.
我需要一个HttpContext的模拟单元测试.但我正在努力.
我正在做一个方法,通过使用SessionIdManager以编程方式更改sessionId.
而SessionIdManager需要HttpContext不是HttpContextBase.
但是我找不到任何可以做出HttpContext模拟的例子.所有的例子只是让HttpContextBase.
我尝试下面,但他们没有工作
HttpContext httpContext = Mock<HttpContext>(); HttpContext httpContext = (HttpContext)GetMockHttpContextBase(); public HttpContextBase GetMockHttpContextBase() { var context = new Mock<HttpContextBase>(); var request = new Mock<HttpRequestBase>(); var response = new Mock<HttpResponseBase>(); var session = new Mock<HttpSessionStateBase>(); var application = new Mock<HttpApplication>(); var httpContext = new Mock<HttpContext>(); var server = new Mock<HttpServerUtilityBase>(); var user = new Mock<IPrincipal>(); var identity = new Mock<IIdentity>(); var urlHelper = new Mock<UrlHelper>(); var routes = new RouteCollection(); var requestContext = new Mock<RequestContext>(); requestContext.Setup(x => x.HttpContext).Returns(context.Object); context.Setup(ctx => ctx.Request).Returns(request.Object); context.Setup(ctx => ctx.Response).Returns(response.Object); context.Setup(ctx => ctx.Session).Returns(session.Object); application.Setup(x => x.Context).Returns(httpContext.Object); context.Setup(ctx => ctx.ApplicationInstance).Returns(application.Object); context.Setup(ctx => ctx.Server).Returns(server.Object); context.Setup(ctx => ctx.User).Returns(user.Object); user.Setup(ctx => ctx.Identity).Returns(identity.Object); identity.Setup(id => id.IsAuthenticated).Returns(true); identity.Setup(id => id.Name).Returns("test"); request.Setup(req => req.Url).Returns(new Uri("http://tempuri.org")); request.Setup(req => req.RequestContext).Returns(requestContext.Object); requestContext.Setup(x => x.RouteData).Returns(new RouteData()); request.SetupGet(req => req.Headers).Returns(new NameValueCollection()); return context.Object; }
有没有办法使HttpContext模拟或使用HttpContextBase进行HttpContext?
请帮助我任何人.
解决方法
这是一个常见的问题,问题的根源是你不要拥有的类型.而不是复杂的嘲笑来尝试和重现你没有写的类的行为(这意味着你猜测它的作用和你需要模拟的),在你的代码和外部对象HttpContext和mock之间引入一个抽象那个抽象.作为模拟对象的先驱之一说:
The key for me was when Joe Walnes came up with the radical notion of
“Don’t mock types you don’t own”. This means: stop jumping through
hoops to work with closed-world libraries,use the tests to discover
your objects and what they say to each other.
http://higherorderlogic.com/2004/02/the-big-idea-is-messaging/