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?
Found the solution. You have to remove your class derived from DbContext and all the DbContextOptions.
Example
services =>
{
var context = services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(MyDbContext));
if (context != null)
{
services.Remove(context);
var options = services.Where(r => (r.ServiceType == typeof(DbContextOptions))
|| (r.ServiceType.IsGenericType && r.ServiceType.GetGenericTypeDefinition() == typeof(DbContextOptions<>))).ToArray();
foreach (var option in options)
{
services.Remove(option);
}
}
services.AddDbContext<MyDbContext>(opt => opt.UseInMemoryDatabase(@"TestDB"));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With