C# - How to setup WebApplicationFactory in .Net 6 without a startup.cs file

Prior to .Net 6 you would have a startup.cs class to set up your asp.net application. In .Net 6 the standard is now to do this within your program.cs file. You can still choose to use a startup class with WebApplicationFactory and not migrate your applications, but this post is for new applications or migrating old ones to the new format.

Prior to .Net 6 you would do something like the following to start your application for testing:

var webApplicationFactory = new WebApplicationFactory<TestRestApplication.Startup>();
var client = webApplicationFactory.CreateClient();

You would create a new WebApplicationFactory and give it your startup class as a generic parameter. But in .Net 6, per default there is no startup.cs.

How to do the same in .Net 6 without startup.cs

Since program.cs is internal it has to be made available to your test project. This can be done using InternalsVisibleTo:

<ItemGroup>
   <InternalsVisibleTo Include="TestProject1" />
</ItemGroup>

Alternatively you can make the program.cs class public:

app.Run();
public partial class Program { } // this part

From here you can do what you did previously with WebApplicationFactory, but you use your program class instead:

var webApplicationFactory = new WebApplicationFactory<Program>();
var client = webApplicationFactory.CreateClient();

That is all there is to it. This worked for me, let me know what you think down in the comments below!