I recently did some refactoring of my mvc application and realized that there are alot of static views returned. Instead of having multiple controllers with action results that only return a view I decided to create one controller that returns the static views if they exists and throws a 404 error if the view doesn't exist.
public ActionResult Index(string name)
{
ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, name, null);
if (result.View == null)
ThrowNotFound("Page does not exists.");
return View(name);
}
My question is what is the right way of unit testing this? I tried the following code but the error I get is "The RouteData must contain an item named 'controller' with a non-empty string value".
[Theory]
[InlineData("ContactUs")]
public void Index_should_return_view_if_view_exists(string name)
{
controller = new ContentController();
httpContext = controller.MockHttpContext("/", "~/Content/Index", "GET"); ;
var result = (ViewResult)controller.Index(name);
Assert.NotNull(result.View);
}
My intention was for the unit test to go out and fetch the real view. Then I started to wonder if I should mock the ViewEngines with SetupGet for FindView and create two tests, where the second one tests that the not found exception is thrown if the view is null.
What is the correct way of testing this functionality? Any pointers, sample code or blog posts would be helpful.
Thanks