SHARE:

ASP.NET Core 7: Better Minimal endpoints testing with typed results

Introduction

ASP.NET Core 7 bring another great improvement on Minimal APIs, especially on unit testing. if you knew how to use IResult static methods such as Results.Ok or Results.NotFound etc…. now you can use them as types that are exposed publicly. What does it mean? You have access now to the types Ok, NotFound etc and you’ll be able to test the type of a returned response from a minimal endpoint. In this post I will show you how to take advantage of them for better unit testing.

Write a unit testable Minimal endpoint

Let’s take a simple example. Let’s consider an endpoint /UnitTestable, where its implementation is made in a separate static class, where the method name is GetPerson and returns a Person object that has two properties: FirstName and LastName. These properties are both filled from HttpContext with is accessed from IHttpContextAccessor injected by dependency. The code will be:

The Program.cs file would look like this:

Unit test a Minimal endpoint

it’s time to unit test it! To make it possible we had to write the endpoint into a separate static class, now we need to unit test its output which should a Ok<Person> object. Remember, since typed result are accessible publicly we can now access to the following types: Ok<T>, NotFound<T> etc…. Your unit test won’t need to importe any Nuget packages for this, simply import yout ASP.NET Core 7 project into your unit test project as follow:

In your unit test class reference the Microsoft.AspNetCore.Http.HttpResults namespace and you are good to go! Not that my unit test uses NSusbstitute to mock IHttpContextAccessor, ExpectedObjects to compare objects by values and not by their reference. The unit test would look like this:

As you can see I can compare the output of my static GetPerson method by casting it into a Ok<Person> object. If the cast fails the result will be Null.

Great improvement right ? 😉

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.