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?
I found the following simple solution for specifying a user in the HttpContext: https://forums.asp.net/post/5828182.aspx
If you're using the MVC framework, this should work. I used Milox's FakeHttpContext and added a few additional lines of code. The idea came from this post:
http://codepaste.net/p269t8
This seems to work in MVC 5. I haven't tried this in earlier versions of MVC.
I worte something about this a while ago.
Unit Testing HttpContext.Current.Session in MVC3 .NET
Hope it helps.
I was looking for something a little less invasive than the options mentioned above. In the end I came up with a cheesy solution, but it might get some folks moving a little faster.
First I created a TestSession class:
Then I added an optional parameter to my controller's constructor. If the parameter is present, use it for session manipulation. Otherwise, use the HttpContext.Session:
Now I can inject my TestSession into the controller:
The answer that worked with me is what @Anthony had written, but you have to add another line which is
so you can use this:
You can try FakeHttpContext: