SparkyTestHelpers: ASP.NET MVC ViewComponents and Async

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

“A sink” (rimshot)

NuGet package | Source code — .NET Framework version

NuGet package | Source code — .NET Core version


In addition to Razor Pages, unit test helpers for which I blogged about a few days ago, The .NET Core framework for ASP.NET MVC has another nice new tool, ViewComponents, a powerful alternative to partial views.

The ViewComponent test helper classes have a lot of similarities with their Controller and Razor PageModel counterparts:

ViewComponentTester<TViewComponent> methods

  • .Invocation(synchronous Invoke method expression)
  • .Invocation(async InvokeAsync method expression)

ViewComponentInvocationTester methods

  • .ExpectingViewName(string expectedViewName) — used with .TestView
  • .ExpectingModel<TModelType>(Action<TModelType> validate) — used with .TestView
  • .TestContent(Action<ContentViewComponentResult> validate)
  • .TestHtmlContent(Action<HtmlContentViewComponentResult> validate)
  • .TestView(Action<ViewViewComponentResult> validate)
  • .TestResult<TViewComponentResultType>(Action<TViewComponentResultType> validate)
  • WhenModelStateIsValidEquals(bool isValid) — used to test conditional logic based on ModelState.IsValid

All validate “callback” actions shown above are optional.

Example code

using SparkyTestHelpers.AspNetMvc
. . .
new ViewComponentTester<FooViewComponent>()
.Invocation(x => x.Invoke)
.ExpectingViewName("Default")
.ExpectingModel(model => Assert.IsTrue(model.Baz))
.TestView();
new ViewComponentTester<FooViewComponent>()
.Invocation(x => x.Invoke)
.WhenModelStateIsValidEquals(false)
.ExpectingViewName("Errors")
.TestView();
new ViewComponentTester<BarViewComponent>()
.Invocation(x => x.InvokeAsnyc)
.TestView();

Asynchronous ViewComponent Invoke methods are encouraged, and writing the test helpers to support async methods made me realize that I should do the same for my ControllerTester and PageModelTester classes, so the NuGet packages have been updated to make that syntax easier.


Happy Testing!