Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7607345
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T00:38:22+00:00 2026-05-31T00:38:22+00:00

I have a web service I am trying to unit test. In the service

  • 0

I have a web service I am trying to unit test. In the service it pulls several values from the HttpContext like so:

 m_password = (string)HttpContext.Current.Session["CustomerId"];
 m_userID = (string)HttpContext.Current.Session["CustomerUrl"];

in the unit test I am creating the context using a simple worker request, like so:

SimpleWorkerRequest request = new SimpleWorkerRequest("", "", "", null, new StringWriter());
HttpContext context = new HttpContext(request);
HttpContext.Current = context;

However, whenever I try to set the values of HttpContext.Current.Session

HttpContext.Current.Session["CustomerId"] = "customer1";
HttpContext.Current.Session["CustomerUrl"] = "customer1Url";

I get null reference exception that says HttpContext.Current.Session is null.

Is there any way to initialize the current session within the unit test?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T00:38:24+00:00Added an answer on May 31, 2026 at 12:38 am

    We had to mock HttpContext by using a HttpContextManager and calling the factory from within our application as well as the Unit Tests

    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;
        }
    }
    

    You would then replace any calls to HttpContext.Current with HttpContextManager.Current and have access to the same methods. Then when you’re testing, you can also access the HttpContextManager and mock your expectations

    This is an example using 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;
    }
    

    and then to use it within your unit tests, I call this within my Test Init method

    HttpContextManager.SetCurrentContext(GetMockedHttpContext());
    

    you can then, in the above method add the expected results from Session that you’re expecting to be available to your web service.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to call a web service from asp.net 3.5 application. I have
I have a web service I'm trying to hit, URL looks like this: http://servername/webapp/ws/invoices/{invoiceid}
I have a web service I'm trying to load test. I created a program
I have a web service that I am trying to test in Visual Web
I'm trying to unit test a java WFS web service implementation. The service can
I have a web service and I'm trying to get data by JSON. if
I have a java web service I am trying to support java isn't really
I have a web service built for SharePoint 2007 that I am trying to
I have a simple web service method which I'm trying to convert: <WebMethod()> _
I have created a web service which returns some data and am trying to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.