This post is about implementing unit testing ASP.NET Core Minimal APIs. This feature is only available in .NET Core 7 Preview. If you’re using .NET Core 6. This will not work. So first you need to install the .NET 7 preview. For the demo I am using this 7.0.100-preview.6.22352.1 version. Once it is done, we need to create a solution, web api with minimal api support and xunit test. Here are the commands.
Since there is no controllers and we can’t create instance of Program.cs we need to refactor the code to support unit testing. So we can refactor the logic to an extension method and we can test this extension method in the Unit Test. So I refactored the existing code like this.
In the GetWeatherforecasts() method, I am using TypedResults.Ok not the Results.Ok - this is a new type introduced in .NET 7.0.
And modify the Program.cs file like this.
Next we can add reference of Web API project to the unit test project. We can do this using dotnet add reference ..\Weatherforecast.Api\ command - this command should be run inside the Weatherforecast.Tests folder. We may need to make the WeatherForecast record to public as well in the API project. Next delete the default test class and create a class with name WeatherForecastTests.cs. And add the following code.
And now we are ready to execute the tests. We can run it using the dotnet test command. And here is the test execution screenshot.
It is a hello world unit test. Here is a little complex a unit test with authentication and database context. Here is the code.
And here is the unit tests for the method.
In the code I am creating the instance of TestDbContextFactory() - which is implemented like this.
And the HttpContext can be used like this.
Update : Based on the suggestion from David Fowler, I am using ClaimsPrincipal object instead of HttpContext. So we can directly use the user object. No need to use the DefaultHttpContext object.
This way we can test Minimal APIs. As I mentioned earlier this features are only available in .NET 7.0. I got a Todo Web API and Unit tests source code in GitHub. In this sample I am using ASP.NET Core 7.0 features, Unit Tests and Code Coverage for unit tests. Also Github action for building, running and deploying web app. Here is the screenshot of the GitHub Action running with code coverage.