9

I need to write some unit tests for an ASP.NET 6 API and need to create a test server to verify authorization. However since the startup class has been removed, I don't know what I should use as the entry point for the test server creation. This was the way of creating one in previous versions.

 var server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
ThomasMand
  • 151
  • 1
  • 7
  • The fact that the start-up class has been removed to show off the new feature of the language does not mean that you can't put it back. – Sergey Kalinichenko Nov 09 '21 at 11:55
  • 1
    The `UseStartup()` method is still there, the ASP.NET team just decided to showcase the new language features and add everything to the `Program` file, this doesn't mean you can't put it back, which I urge you to do if you want to re-use code – MindSwipe Nov 09 '21 at 11:59

2 Answers2

7

You can use WebApplicationFactory (which, based on docs, is a wrapper around TestServer and exposes properties and methods to create and get it like CreateServer and Server) for your integration tests. To set up it with the new minimal hosting model you need to make you web project internals visible to the test one for example by adding next property to csproj:

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

And then you can inherit your WebApplicationFactory from the generated Program class for the web app:

class MyWebApplication : WebApplicationFactory<Program>
{
    protected override IHost CreateHost(IHostBuilder builder)
    {
        // shared extra set up goes here
        return base.CreateHost(builder);
    }
}

And then in the test:

var application = new MyTestApplication();
var client = application.CreateClient();
var response = await client.GetStringAsync("/api/WeatherForecast");

Or use WebApplicationFactory<Program> from the test directly:

var application = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
    builder .ConfigureServices(services =>
    {
       // set up servises
    });
});
var client = application.CreateClient();
var response = await client.GetStringAsync("/api/WeatherForecast");

Code examples from migration guide.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
6

The issue ended up being that by default Program.cs isn't discoverable, so I ended up adding this to the ASP.Net .csproj file.

<ItemGroup>
    <InternalsVisibleToInclude="{Insert testing project name here}" />
</ItemGroup>

And adding

public partial class Program { }

To the bottom of the Program.cs file

ThomasMand
  • 151
  • 1
  • 7