13

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);
}
Rob
  • 6,731
  • 12
  • 52
  • 90

4 Answers4

17

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).

Anton
  • 5,323
  • 1
  • 22
  • 25
  • Thanks for the response! This did it, though i modified the simpleworkerrequest a little by adding the right path and adresses. – Rob Jul 14 '10 at 06:19
2

You can try looking at the attributes created for ASP.Net unit testing, like

[HostType("ASP.NET")]

This link to MSDN has quite a good write-up about it

EggyBach
  • 4,148
  • 1
  • 18
  • 21
2

You could decorate your test method with the followings attributes:

[TestMethod]
[HostType("ASP.NET")]
[UrlToTest("http://localhost:xxxx/")]
[AspNetDevelopmentServerHost("$(SolutionDir)\\xxx\\", "/")]
public void TestMethod()
{
   ...
}

Then adding a Default.aspx file into your unit test proj.

Inside the test method you can easily access to the HttpContext. If you want to debug, you may use some traces or interrupt the debugging execution with the instruction System.Diagnostics.Debugger.Break()

public void TestMethod()
{
   System.Diagnostics.Debugger.Break();

   ...
}

and then attaching debugger to the process as explained by MSDN: https://msdn.microsoft.com/en-us/library/vstudio/c6wf8e4z(v=vs.100).aspx

1

I'm posting this for reference. It's not an easy solution, and talks about Duck Typing (if it quacks..):

http://haacked.com/archive/2007/08/19/why-duck-typing-matters-to-c-developers.aspx

http://haacked.com/archive/2007/09/09/ihttpcontext-and-other-interfaces-for-your-duck-typing-benefit.aspx

It's relevant and worth a read; because there's no IHttpContext it's not possible to create a test environment implementation - until you consider using the Duck Typing library here. Though this is not a direct answer.

Hope that helps.

Kieren Johnstone
  • 41,277
  • 16
  • 94
  • 144