1

With .NET 5 I used the following in my nUnit [SetUp] for each test. This created a host and a client with which I could call my API with full integrations as defined in the Startup:

Microsoft.AspNetCore.TestHost.TestServer _testServer;

HttpClient _testClient;

[SetUp]
public async Task SetUp()
{
    // Load up test configuration
    IConfiguration config = new ConfigurationBuilder()
        .SetBasePath("mypath")
        .AddJsonFile("integrationsettings.json")
        .Build();

    // Create the host (using startup)
    WebHostBuilder builder = new WebHostBuilder()
        // Use startup from WebApp Server project
        .UserStartup<MyWebApp.Startup>()
        // Configure logging from integrationsettings.json
        .ConfigureLogging((hostingContext, logging) =>
            logging.AddConfiguration(config.GetSection("Logging"))
        // Set core app configuration to use integrationsettings.json
        .ConfigureAppConfiguration(cfg => cfg.AddConfiguration(config))
        // Add any additional services not loaded by startup
        .ConfigureServices(services => // add additional services not laoded in Startup);

    // Create the Server
    _testServer = new TestServer(builder);

    // Create the Client
    _testClient = _testServer.CreateClient();
}

I could then use testClient HttpClient to work directly with my API.

Life was sweet.

I know I could still use the old model with .NET 6 (Program.cs + Startup.cs), but if I'm going to go with the flow, now that we have minimal API with just the Program.cs, how do I replicate the above?

From what I can gather, it looks like WebApplicationFactory is the key, but have not found anything that gets me over the line.

Is it as simple as adding the assembly that contains WebApplication and just build the app in test SetUp in the same way as I do in Program.cs on the server?

Is there a way to encapsulate the build logic (much like the old Startup.cs) so I do not need to duplicate the configuration used on the server in my tests?

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Neil W
  • 7,670
  • 3
  • 28
  • 41
  • 1
    have you tried approach from [this](https://stackoverflow.com/questions/70093628/integration-test-and-hosting-asp-net-core-6-0-without-startup-class/70095604#70095604) answer? – Guru Stron Dec 10 '21 at 15:01
  • @GuruStron ... thanks for that link. So, the code we see in the new Program.cs file in the minimal project, even though not identified in any curly bracket classification, is implicitly an `internal class Program`? And the class derived from `WebApplicationFactory` will reuse the code in the server's Program.cs file with the option to add additional configuration for tests in the `CreateHost` method? – Neil W Dec 10 '21 at 16:28
  • Have followed the guidance in your other post and all is good! Thank you! – Neil W Dec 10 '21 at 17:03
  • Glad it helped! – Guru Stron Dec 15 '21 at 12:43

0 Answers0