1

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

 1 year ago
source link: https://anthonygiretti.com/2023/03/19/asp-net-core-7-better-minimal-endpoints-testing-with-typed-results/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

2023-03-19 by anthonygiretti

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:

image-3.png

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 ? 😉

Like this:

Loading...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK