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.
Here is my current test file:
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);
}
}
}
Here's Controllers/HomeController.cs:
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();
}
}
}
When I run the test, it fails, since result.ViewName is null. It looks like result is just an empty ViewResult with nothing to do with _homeController. What do I need to do to get the test to find the Index view in HomeController?