3
votes

I have application that designed to be standalone aspnet core webapi self host executable.

To start the executable a config file path MUST be pass as command line argument (e.g. MyServer.exe --config "path-to-config-file")

I would like to test it via integration tests (Following this page: https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.1)

My question - how does command line arguments are passed to WebApplicationFactory?

Thank you

1

1 Answers

8
votes

Command-line arguments are handled by the command-line configuration provider. In other words, the end result is that you simply end up with those values in your configuration root, and that's where you'd access them from later to utilize them. Given that, you can simply use any means of configuration in test to provide the same value, or even just write directly to the configuration.

If you haven't already, you should subclass your Startup class specifically for testing, i.e. something like:

public class TestStartup : Startup
{
    public TestStartup(IConfiguration configuration)
        : base(configuration)
    {

    }
}

Then, inside your TestStartup constructor, you can set the appropriate value in your configuration:

configuration["config"] = "path-to-config-file";

Just bear in mind that the type param to WebApplicationFactory is simply used to determine the "entry point", i.e. which Program the test host is going to run to bootstrap itself. As a result, you should continue to use WebApplicationFactory<Startup>, but then configure your test host to use your TestStartup instead:

public MyTests(WebApplicationFactory<Startup> factory)
{
    factory = factory.WithWebHostBuilder(builder => builder.UseStartup<TestStartup>());
}