title: How do I mock controller context in my unit test so that my partial view to string function works?
body: <p>I am attempting to create a unit test for my controller, but the action I am testing uses a partial view to string function which doesn't want to work in my tests.</p>
  
  <pre><code>private string RenderPartialViewToString(string viewName, object model = null)
  {
     if (string.IsNullOrEmpty(viewName))
              viewName = ControllerContext.RouteData.GetRequiredString("action");
  
     ViewData.Model = model;
  
     using (System.IO.StringWriter sw = new System.IO.StringWriter())
     {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);
  
        return sw.GetStringBuilder().ToString();
     }
  }
  </code></pre>
  
  <p>This gives me an error of "Object reference not set to an instance of an object" on the line <code>ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);</code></p>
  
  <p>My setup in the unit test for the controller is (with a few bits removed to simplify it):</p>
  
  <pre><code>var mock = new Mock&lt;ControllerContext&gt;();
  mock.SetupGet(p =&gt; p.HttpContext.User.Identity.Name).Returns(userName);
  if (userName != null)
  {
     mock.SetupGet(p =&gt; p.HttpContext.Request.IsAuthenticated).Returns(true);
     mock.SetupGet(p =&gt; p.HttpContext.User.Identity.IsAuthenticated).Returns(true);
  }
  else
  {
     mock.SetupGet(p =&gt; p.HttpContext.Request.IsAuthenticated).Returns(false);
  }
  var controller = new BlogController();
  controller.ControllerContext = mock.Object;
  </code></pre>
  
  <p>I've not had any luck trying to find a solution or work around. Any help appreciated. Thanks.</p>
  
  <hr>
  
  <p>As suggested I have tried setting up route data but still getting the error. This is what I have added:</p>
  
  <pre><code>var routeData = new RouteData();
  routeData.Values.Add("controller", "BlogController");
  mock.SetupGet(m =&gt; m.RouteData).Returns(routeData);
  </code></pre>