title: Mock HttpContext using moq for unit test
body: <p>I need a mock of HttpContext for unit testing. But I'm struggling with it.</p>
  
  <p>I'm making a method that would change sessionId by programmatically with SessionIdManager.
  And SessionIdManager requires HttpContext not HttpContextBase.</p>
  
  <p>But I couldn't find any example to make a mock of HttpContext. All examples out there are only to make HttpContextBase.</p>
  
  <p>I tried below but they didn't work</p>
  
  <pre><code>HttpContext httpContext = Mock&lt;HttpContext&gt;();
  HttpContext httpContext = (HttpContext)GetMockHttpContextBase();
  
  public HttpContextBase GetMockHttpContextBase()
  {
     var context = new Mock&lt;HttpContextBase&gt;();
     var request = new Mock&lt;HttpRequestBase&gt;();
     var response = new Mock&lt;HttpResponseBase&gt;();
     var session = new Mock&lt;HttpSessionStateBase&gt;();
     var application = new Mock&lt;HttpApplication&gt;();
     var httpContext = new Mock&lt;HttpContext&gt;();
     var server = new Mock&lt;HttpServerUtilityBase&gt;();
     var user = new Mock&lt;IPrincipal&gt;();
     var identity = new Mock&lt;IIdentity&gt;();
     var urlHelper = new Mock&lt;UrlHelper&gt;();
     var routes = new RouteCollection();
     var requestContext = new Mock&lt;RequestContext&gt;();
  
     requestContext.Setup(x =&gt; x.HttpContext).Returns(context.Object);
     context.Setup(ctx =&gt; ctx.Request).Returns(request.Object);
     context.Setup(ctx =&gt; ctx.Response).Returns(response.Object);
     context.Setup(ctx =&gt; ctx.Session).Returns(session.Object);
     application.Setup(x =&gt; x.Context).Returns(httpContext.Object);
     context.Setup(ctx =&gt; ctx.ApplicationInstance).Returns(application.Object);
     context.Setup(ctx =&gt; ctx.Server).Returns(server.Object);
     context.Setup(ctx =&gt; ctx.User).Returns(user.Object);
     user.Setup(ctx =&gt; ctx.Identity).Returns(identity.Object);
     identity.Setup(id =&gt; id.IsAuthenticated).Returns(true);
     identity.Setup(id =&gt; id.Name).Returns("test");
     request.Setup(req =&gt; req.Url).Returns(new Uri("http://tempuri.org"));
     request.Setup(req =&gt; req.RequestContext).Returns(requestContext.Object);
     requestContext.Setup(x =&gt; x.RouteData).Returns(new RouteData());
     request.SetupGet(req =&gt; req.Headers).Returns(new NameValueCollection());
  
     return context.Object;
  }
  </code></pre>
  
  <p>Is there any way to make mock of HttpContext or to use HttpContextBase for HttpContext?</p>
  
  <p>Please help me anyone.</p>