2

I want to test ASP.NET Core 6 application. I have created a custom factory as inheriting from WebApplicationFactory, in ConfigureWebHost method, do I have to use builder.ConfigureServices or builder.ConfigureTestService ?

I don't understand the difference.

E.g :

        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder
                .ConfigureTestServices(services => //Or ConfigureServices ?
                {
                    var descriptor = services.SingleOrDefault(
                        d => d.ServiceType ==
                            typeof(DbContextOptions<OnDemandContext>));

                    if (descriptor != null)
                    {
                        services.Remove(descriptor);
                    }
                    
                    services.AddDbContextPool<OnDemandContext>(options =>
                    {
                        options.UseInMemoryDatabase("fakeDatabase");
                    });
                });
        }
Julien Martin
  • 197
  • 2
  • 15
  • 2
    You could check this issue:https://stackoverflow.com/questions/43543319/reconfigure-dependencies-when-integration-testing-asp-net-core-web-api-and-ef-co/50434512#50434512 ConfigureTestServices allows you override existing registrations with mocks which could be done by WebHostBuilder.ConfigureServices as well – Ruikai Feng Aug 24 '22 at 07:13

1 Answers1

4

You don't have to call builder.ConfigureTestServices but it will allow you to re-configure, override, or replace previously registered services with something else. It is executed after your ConfigureServices method is called.

In the example below, testcontainers are used to replace the normal database connection string provider and a WebMotions.Fake.Authentication.JwtBearer is being used to create a fake Jwt bearer token for integration testing

    builder.ConfigureTestServices(services =>
    {
        services.AddAuthentication(FakeJwtBearerDefaults.AuthenticationScheme).AddFakeJwtBearer();
        services.RemoveAll(typeof(IHostedService));
        services.RemoveAll(typeof(IConnectionStringProvider));
        var containerString = new ConnectionStringOptions
        {
            Application = "testContainer",
            Primary = Container.ConnectionString
        };
        services.AddSingleton<IConnectionStringProvider>(_ =>
            new ConnectionStringProvider(containerString));
    });
David Rinck
  • 6,637
  • 4
  • 45
  • 60