Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using httpcontext in unit test

I'm using C#4.0 and i need to unit test a service. The function inside the service returns a path similar to the variable i called expected, this is the path i'm expecting to get back. But when i run this test i'm getting the error that HttpContext.Current is NULL. What can i do to fix this issue so the test can be ran?

[TestMethod]
public void GetPathTest()
{
   var expected = System.IO.Path.GetFullPath(HttpContext.Current.Server.MapPath("~/Certificates/"));
   var path = _mockService.Setup(o => o.GetPath()).Returns(expected);
}
like image 971
Rob Avatar asked Jul 13 '10 06:07

Rob


1 Answers

At the moment I can't find my full wrapper for HttpContext that I used earlier, but at the moment we simply create a context for an empty request and go from there, like this:

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

Then in the unit test initialize or in the unit test itself (before you create expected) you can set the current HttpContext as follows:

HttpContext.Current = context;

Then simply flesh out the fake context and possible fake sessionstate, etc as required.

(Edit: This is all in VS2008, framework 3.5 by the way).

like image 56
Anton Avatar answered Sep 21 '22 15:09

Anton