Xavier John
Xavier John

Reputation: 9477

Remove DbContext from DI. Testing with WebApplicationFactory<Startup>

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?

Upvotes: 2

Views: 1886

Answers (1)

Xavier John
Xavier John

Reputation: 9477

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"));
  });

Upvotes: 10

Related Questions