How to avoid HttpContext.Server.MapPath for Unit Testing Purposes
<p>I am working in an ASP.net MVC 5 application. I would like to Unit Test my controller action which looks like this</p>

<pre><code>public ActionResult Search()
{
  var vm = SetupSearchViewModel();

  return View(vm);
}
</code></pre>

<p>All the hard work is done by the <code>SetupSearchViewModel()</code> method, which itself is an orchestrator calling many different other methods, one of which is this</p>

<pre><code>private string ExtractJsonFile(string filename)
{
  var filePath = HttpContext.Server.MapPath(filename);
  var json = System.IO.File.ReadAllText(filePath);
  return json;
}
</code></pre>

<p>I plan on doing many Unit Tests on this particular action, but I'm starting with a very simple Unit Test which checks that the correct type of ActionResult is returned</p>

<pre><code>[Test]
public void Search_Get_ReturnsViewResult()
{
  // arrange
  var performanceController = PerformanceControllerInstance;
  // act
  var result = performanceController.Search();
  //assert
  Assert.IsNotNull(result as ViewResult);
}
</code></pre>

<p>The test is failing because of the <code>ExtractJsonFile</code> method. It uses <code>HttpContext</code> and that is <code>null</code>. I am using Rhino Mocks to do the mocking of the various classes.</p>

<p>What would be the best way to Unit Test this? Darin in <a href="https://stackoverflow.com/questions/5377626/mock-httpcontext-current-server-mappath-using-moq">this thread</a> suggest we avoid <code>HttpContext.Current</code> if we want our code Unit Tested.</p>

<p>By the way I tried mocking the HttpContext and made it not null, but then the <code>Server</code> is <code>null</code>, I can go ahead and mock that too I suppose (I don't know how yet), but is there no better way? I've no problem doing major refactoring if needed.</p>