BaltoStar
BaltoStar

Reputation: 8977

ASP.NET Core integration tests

I'm following the pattern from this MS doc :

https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2

public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<Startup>
{
    protected override IWebHostBuilder CreateWebHostBuilder()
    {
        return WebHost.CreateDefaultBuilder()
            .UseStartup<Startup>();
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =>
        {
            var serviceProvider = new ServiceCollection()
                .AddEntityFrameworkInMemoryDatabase()
                .BuildServiceProvider();

            services.AddDbContext<MyDbContext>(options =>
            {
                options.UseInMemoryDatabase("MyDb");
                options.UseInternalServiceProvider(serviceProvider);
            });

            serviceProvider = services.BuildServiceProvider();

            using (var scope = serviceProvider.CreateScope())
            {
                var scopedProvider = scope.ServiceProvider;
                var myDb = scopedProvider.GetRequiredService<MyDbContext>();
                var logger = scopedProvider.GetRequiredService<ILogger<CustomWebApplicationFactory<TStartup>>>();

                myDb.Database.EnsureCreated();
            }
        });

        builder.UseContentRoot(".");
        base.ConfigureWebHost(builder);
    }
}

but on this line

var myDb = scopedProvider.GetRequiredService<MyDbContext>();

I'm receiving error

Entity Framework services have not been added to the internal service provider. Either remove the call to UseInternalServiceProvider so that EF will manage its own internal services, or use the method from your database provider to add the required services to the service provider (e.g. AddEntityFrameworkSqlServer).

This makes no sense to be because I believe I am adding EF services to the internal service provider on this line :

var serviceProvider = new ServiceCollection()
    .AddEntityFrameworkInMemoryDatabase()
    .BuildServiceProvider();

Upvotes: 1

Views: 1811

Answers (1)

Shahzad Hassan
Shahzad Hassan

Reputation: 1003

That's because you are using:

var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider();

The above will get overridden by the following line as AddEntityFrameworkInMemoryDatabase() is not part of the services parameter.

serviceProvider = services.BuildServiceProvider();

Replace the above with:

//Build the service provider.
var sp = services.BuildServiceProvider();

Then create the scope using sp. I hope that helps

Upvotes: 2

Related Questions