.NET 6 introduces a new way to write your API’s without the need of a Startup.cs file.
More about ‘Minimal APIs’ as this feature is called can be found here:
- https://docs.microsoft.com/en-us/aspnet/core/tutorials/min-web-api?view=aspnetcore-6.0
- https://docs.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-6.0
But how do you write an integration test for such a minimal API?
Before you used the WebApplicationFactory<TStartup> and specified the Startup.cs as the generic argument of the factory. But now the Startup.cs file is gone.
Luckily Microsoft thought about this and updated the Microsoft.AspNet.Mvc.Testing package to work without it. I find the solution not very clean but at least it works.
Here are the steps you need to take:
- Microsoft made it possible to use the Program.cs file as the generic argument instead of the Startup.cs file. Unfortunately by default the Program.cs file is internal so we have to make some changes. You have 2 options. Either you expose your internal types from the web app to the test project. This can be done in the project file (
.csproj
):This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters<ItemGroup> <InternalsVisibleTo Include="MyAPI.Tests" /> </ItemGroup> - Or you can make the
Program
class public by using a partial class declaration. Add the following code line to the end of your Program.cs file:This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characterspublic partial class Program { }
Now you can use the Program
class for the WebApplicationFactory:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class APITests: IClassFixture<WebApplicationFactory<Program>> | |
{ | |
[Fact] | |
public void Test1() | |
{ | |
} | |
} |