SparkyTestHelpers: AspNetMvc

part of the “SparkyTestHelpers” suite of .NET unit testing tools

“Classic MVC”: Mozart Violin Concerto

NuGet package | Source code — .NET Framework version

NuGet package | Source code — .NET Core version


These NuGet packages (one for the “classic” ASP.NET MVC Framework and one for ASP.NET Core MVC) contain helpers for testing that MVC controller actions return the expected results:

ControllerTester<TController>

Instantiation:

using SparkyTestHelpers.AspNetMvc
var homeController = new HomeController(/* w/test dependencies */);
var controllerTester =
new ControllerTester<HomeController>(homeController);

It doesn’t do anything on its own — just provides an Action(actionDefinitionExpression) method that’s used to create a…

ControllerActionTester

var controllerActionTester = 
new ControllerTester<HomeController>(homeController)
.Action(x => x.Index);

ControllerActionTester has several .Test… methods used to assert that the controller action returns the expected ActionResult implementation. There are methods for all of the standard result types, plus the generic TestResult<TActionResultType> method:

  • .TestContent(Action<ContentResult> validate)
  • .TestEmpty(Action<EmptyResult> validate)
  • .TestFile(Action<FileResult> validate)
  • .TestJson(Action<JsonResult> validate)
  • .TestPartialView(Action<PartialViewResult> validate)
  • .TestRedirect(string expectedUrl, Action<RedirectResult> validate)
  • .TestRedirectToAction(string expecteActionName, Action<RedirectToRouteResult> validate)
  • .TestRedirectToRoute(string expectedRoute, Action<RedirectToRouteResult> validate)
  • .TestView(Action<ViewResult> validate)
  • .TestResult<TActionResultType>(Action<TActionResultType> validate)

Additional methods:

  • .ExpectingViewName(string expectedViewName) — used with .TestView and .TestPartialView
  • .ExpectingModel<TModelType>(Action<TModelType> validate) — using with .TestView and .TestJson
  • WhenModelStateIsValidEquals(bool isValid) — used to test conditional logic based on ModelState.IsValid

All validate “callback” actions shown above are optional.

Examples

var homeController = new HomeController(/* w/test dependencies */);
var controllerTester =
new ControllerTester<HomeController>(homeController);
controllerTester.Action(x => x.Index).TestView();
controllerTester
.Action(x => () => x.Details(3))
.ExpectingViewName("Details")
.ExpectingModel<Foo>(foo => Assert.IsTrue(foo.IsValid))
.TestView();
controllerTester
.Action(x => () => x.Edit(updateModel))
.WhenModelStateIsValidEquals(false)
.TestRedirectToAction("Errors");
controllerTester
.Action(x => () => x.Edit(updateModel))
.WhenModelStateIsValidEquals(true)
.ExpectingViewName("UpdateSuccessful")
.TestRedirectToRoute("Home/UpdateSuccessful");

Happy Testing!