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?
We had to mock
HttpContextby using aHttpContextManagerand calling the factory from within our application as well as the Unit TestsYou would then replace any calls to
HttpContext.CurrentwithHttpContextManager.Currentand have access to the same methods. Then when you’re testing, you can also access theHttpContextManagerand mock your expectationsThis is an example using Moq:
and then to use it within your unit tests, I call this within my Test Init method
you can then, in the above method add the expected results from Session that you’re expecting to be available to your web service.