我有一个我正在尝试进行单元测试的网络服务。在服务中,它从HttpContext类似的东西中提取几个值:
HttpContext
m_password = (string)HttpContext.Current.Session["CustomerId"]; m_userID = (string)HttpContext.Current.Session["CustomerUrl"];
在单元测试中,我使用简单的工作请求创建上下文,如下所示:
SimpleWorkerRequest request = new SimpleWorkerRequest("", "", "", null, new StringWriter()); HttpContext context = new HttpContext(request); HttpContext.Current = context;
但是,每当我尝试设置HttpContext.Current.Session
HttpContext.Current.Session
HttpContext.Current.Session["CustomerId"] = "customer1"; HttpContext.Current.Session["CustomerUrl"] = "customer1Url";
我得到空引用异常,它说HttpContext.Current.Session是空的。
有没有办法在单元测试中初始化当前会话?
HttpContext我们必须通过使用 a来模拟,HttpContextManager并从我们的应用程序以及单元测试中调用工厂
HttpContextManager
public class HttpContextManager { private static HttpContextBase m_context; public static HttpContextBase Current { get { if (m_context != null) return m_context; if (HttpContext.Current == null) throw new InvalidOperationException("HttpContext not available"); return new HttpContextWrapper(HttpContext.Current); } } public static void SetCurrentContext(HttpContextBase context) { m_context = context; } }
然后,您将替换任何对HttpContext.Currentwith的调用HttpContextManager.Current并可以访问相同的方法。然后,当您进行测试时,您还可以访问HttpContextManager并模拟您的期望
HttpContext.Current
HttpContextManager.Current
这是使用Moq的示例:
private HttpContextBase GetMockedHttpContext() { var context = new Mock<HttpContextBase>(); var request = new Mock<HttpRequestBase>(); var response = new Mock<HttpResponseBase>(); var session = new Mock<HttpSessionStateBase>(); var server = new Mock<HttpServerUtilityBase>(); var user = new Mock<IPrincipal>(); var identity = new Mock<IIdentity>(); var urlHelper = new Mock<UrlHelper>(); var routes = new RouteCollection(); MvcApplication.RegisterRoutes(routes); 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); 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://www.google.com")); 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; }
然后在你的单元测试中使用它,我在我的 Test Init 方法中调用它
HttpContextManager.SetCurrentContext(GetMockedHttpContext());
然后,您可以在上述方法中添加您期望可用于 Web 服务的 Session 的预期结果。