The scenario is .net core 5 Web API, services.AddDbContext is used in Startup.cs ConfigureServices to add SQL server. The test uses the WebApplicationFactory provided by MVC testing, I would like to replace the DbContext with InMemory or point to a test database.
I have tried removing it in the WebApplicationFactory ConfigureWebHost but something is holding on to the SQL DbContext because, when the test runs, it is hitting the SQL server instead of the InMemory database even though SQL DbContext is not there in the DI.
builder.ConfigureTestServices(
services =>
{
var serviceDescriptor = services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(DbContext));
if (serviceDescriptor != null)
{
services.Remove(serviceDescriptor);
}
}
Is there a right way to replace the DbContext added in Startup.cs in the test project?