This post is about implementing integration testing in ASP.NET Core Minimal APIs. Usually when I talk about Minimal APIs, one of the question I used to get is how to implement integration testing and I saw some questions related to this in Stack Overflow as well. In this blog post I am trying to cover implementing ASP.NET Core integration testing with NUnit Framework. This code is can be used in XUnit as well.
First, we need to create web api project, remove controllers folder and add the following code in the program.cs - it is a simple API project with CRUD operations - I omitted Update and Delete operations. I am using Sqlite for this project as the database.
To get started we need to modify the API project file with the InternalsVisibleTo attribute, like this with your test project name.
Next we need to create NUnit project we can use the command dotnet new nunit -o Notes.Api.Tests. In this project, we need to first add the reference of web api project, we can use the dotnet add reference command for this.
For integration testing we need to create instance of WebApplicationFactory class - so we need to install the nuget package Microsoft.AspNetCore.Mvc.Testing. And for mocking the database context we need the Microsoft.EntityFrameworkCore.InMemory nuget package as well. Here is my updated project file.
Now we can implement the WebApplicationFactory class like this.
In the code, I am removing the existing DbContext and using EFCore In Memory database. And you can write a test like this.
In this example, I am checking the Notes which will return zero notes because the in memory database is empty. To use the data, you need to access the database context and can insert data like this.
And we can write test case for creating note like this.
Here is the screen shot when I am running the dotnet test command.
The tests show how you can write integration tests for the Minimal API. You can implement the same code for Razor apps as well. Here are few resources to learn more about Minimal APIs.