I want to test a ASP.NET Core 6 application. I have created a custom factory as inheriting from WebApplicationFactory
. In the 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");
});
});
}
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));
});