ASP.NET Core integration tests

asp.net-core c# entity-framework-core integration-testing

Question

I'm following the pattern from this MS doc :

https://docs.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();
1
1
5/20/2019 1:56:39 AM

Accepted Answer

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

2
5/20/2019 2:40:50 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow