title: Looking for direction on unit testing a controller extension that renders a partial view
body: <p>As the title says, I'm looking for direction on how to properly test a controller extension. The extension renders a partial view which in turn I'm using within a JSONResult:</p>
  
  <pre><code> public static string RenderPartialViewToString(this Controller controller, string viewName = null, object model = null)
          {
              if (string.IsNullOrEmpty(viewName))
              {
                  viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
              }
  
              controller.ViewData.Model = model;
  
              using (StringWriter sw = new StringWriter())
              {
                  ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                  ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                  viewResult.View.Render(viewContext, sw);
                  return sw.GetStringBuilder().ToString();
              }
          }
  </code></pre>
  
  <p>Example usage:</p>
  
  <pre><code>public JsonResult Foo()
  {
      var model = _repository.getSomeData();
  
      return Json(new { html = this.RenderPartialViewToString("Index", model) }, JsonRequestBehavior.AllowGet);
  }
  </code></pre>
  
  <p>I'm using NUnit &amp; the <a href="http://mvccontrib.codeplex.com/wikipage?title=TestHelper" rel="noreferrer">MvcContrib test helper</a>, however when setting up a controller that makes use of this extension I'm running into a NRE. I'm assuming that the controller context is not setup correctly?</p>
  
  <p>Ultimately the test is barfing on <code>ViewEngines.Engines.FindPartialView</code>. Here is a portion of the failing test:</p>
  
  <pre><code>var routeData = new RouteData();
  routeData.Values.Add("controller", "someName");
  routeData.Values.Add("action", "someAction");
  
  var builder = new TestControllerBuilder();
  var controller = new ListingController(repository.Object);
  builder.RouteData = routeData;
  builder.InitializeController(controller);
  
  var result = controller.Foo();
  </code></pre>