SparkyTestHelpers: ASP.NET MVC ViewComponents and Async

Brian Schroer
Apr 2, 2018 · 2 min read

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

Image for post
Image for post
“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:

  • .Invocation(synchronous Invoke method expression)
  • .Invocation(async InvokeAsync method expression)
  • .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.

using SparkyTestHelpers.AspNetMvc
. . .
new ViewComponentTester<FooViewComponent>()
.Invocation(x => x.Invoke)
.ExpectingModel(model => Assert.IsTrue(model.Baz))
new ViewComponentTester<FooViewComponent>()
.Invocation(x => x.Invoke)
new ViewComponentTester<BarViewComponent>()
.Invocation(x => x.InvokeAsnyc)

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!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store