skip to Main Content

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>());

2

Answers


  1. Chosen as BEST ANSWER

    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


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search