title: ASP.NET MVC: testing a controller with XUnit
body: <p>I am trying to use unit testing with XUnit for an ASP.NET v5 MVC v6 app. I can get simple unit testing on methods working. I would like to test Controllers. Right now, I have a HomeController with an Index action that returns the Home/Index view. I want to test that the Index view is the one that is returned.</p>
  
  <p>Here is my current test file:</p>
  
  <pre><code>using Microsoft.AspNet.Mvc;
  using Xunit;
  using XUnitWithMvcSample.Controllers;
  
  namespace XUnitWithMvcSample.Tests
  {
      public class Tests
      {
          private HomeController _homeController;
          public Tests()
          {
              _homeController = new HomeController();
          }
          [Fact]
          public void IndexActionReturnsIndexView()
          {
              var result = _homeController.Index() as ViewResult;
              System.Console.WriteLine(result);
              Assert.Equal("Index", result.ViewName);
          }
  
      }
  }
  </code></pre>
  
  <p>Here's Controllers/HomeController.cs:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Threading.Tasks;
  using Microsoft.AspNet.Mvc;
  
  
  namespace XUnitWithMvcSample.Controllers
  {
      public class HomeController : Controller
      {
          public IActionResult Index()
          {
              return View();
          }
      }
  }
  </code></pre>
  
  <p>When I run the test, it fails, since <code>result.ViewName</code> is null. It looks like <code>result</code> is just an empty <code>ViewResult</code> with nothing to do with <code>_homeController</code>. What do I need to do to get the test to find the Index view in HomeController?</p>