简体   繁体   中英

How can I end to end test this .net core console application?

I have a .Net Core 2.0 console application. The main() method is like this:

public static async Task Main()
{
    // create  host builder
    var hostBuilder = new HostBuilder();
    var myApp = new MyApplication();

    // Build host
    var host = hostBuilder
        .ConfigureHostConfiguration(myApp.ConfigureHostConfiguration)
        .ConfigureServices(myApp.ConfigureServices)
        .ConfigureLogging(myApp.ConfigureLogging)
        .Build();

    // Initialise
    await myApp.InitialiseAppAsync(host);

    // Run host
    await host.RunAsync(CancellationToken.None);
}

The MyApplication class sets up the application configuration in ConfigureHostConfiguration(), it then configures up the dependencies in ConfigureServices() some of which register a Message Handlers to handle specific Messages types from an Azure Service Bus. The application needs to do some initialisation from within InitialiseAppAsync(). When host.RunAsync() is called, the a console application is run indefinitely and the Message Handler receives execution as soon as a message is available on the Azure Service Bus. This is all great and working fine.

What I'd like to do is create a new project under the same solution which contains some end to end tests (using XUnit). I'd like to be able to override some of the dependencies (with test mocks, using NSubstitute), leaving the other dependencies as they are configured in the service.

I'm guessing I'd need to create my own HostBuilder in my test, so I'll need to be able to setup the mocks before the host.RunAsync() call is made within the test.

Does anyone know how I can do this? Or what is the best practice for doing this?

Ultimately, what I'm trying to do is be able to override some (but not all) of my real dependencies in my Console Application with mocks, so I can do some end to end tests.

Thanks in advance

There are multiple ways to achieve this. You can set up the environment variable "environment" when you start up your application. Then you would need to run your application passing it like this:

dotnet "MyApplication.dll" --environment end2endTests

Then you will be able to find the value you passed as the environment at IHostEnvironment instance which is injectable. This is how your DI registrations would look like:

services.AddScoped<IFoo>(provider =>
{
   var env = provider.GetRequiredService<IHostEnvironment>();

   if (env.EnvironmentName == "end2endTests")
   {
      return new TestFoo();
   }
   return new RealFoo();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM