Access in memory dbcontext in integration test
Asked Answered
Q

2

13

How can I access the dbcontext of an in memory database inside an integration test?

I have followed the code here: https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2#customize-webapplicationfactory

and have a similar test to:

public class IndexPageTests : 
    IClassFixture<CustomWebApplicationFactory<RazorPagesProject.Startup>>
{
    private readonly HttpClient _client;
    private readonly CustomWebApplicationFactory<RazorPagesProject.Startup> 
        _factory;

    public IndexPageTests(
        CustomWebApplicationFactory<RazorPagesProject.Startup> factory)
    {
        _factory = factory;
        _client = factory.CreateClient(new WebApplicationFactoryClientOptions
            {
                AllowAutoRedirect = false
            });
    }

In this IndexPageTests is it possible to access the in-memory dbcontext?

I have tried

 using (var context = new ApplicationDbContext(???))

I need to access data from tables i had previously seeded from CustomWebApplicationFactory

but not sure what to put for the options

Quaquaversal answered 7/3, 2019 at 22:41 Comment(4)
You would have to resolve it via the host's services provider. factory.Server.Host.Services.GetService<ApplicationDbContext>()Tessy
@Nkosi, this gives error : Cannot resolve scoped service 'ApplicationDbContext' from root provider.Quaquaversal
@Nikosi, thanks you pointed me in the right direction... had to create scope first _factory.Server.Host.Services.GetService<IServiceScopeFactory>();Quaquaversal
Glad to help. You should add it as a self answer so that others can benefit.Tessy
Q
19

Thanks to Nikosi, this is the way I managed to get the dbcontext

var scopeFactory = _factory.Server.Host.Services.GetService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope())
{
   var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
}
Quaquaversal answered 7/3, 2019 at 23:41 Comment(2)
Add the using using Microsoft.Extensions.DependencyInjection; so you get the GetService<T> and GetRequiredService<T> methodsStunsail
I had to use _factory.Services.GetService<IServiceScopeFactory>() in .NET 6.Psychosocial
P
3

The below worked with me as it didn't throw an exception:

var scope = factory.Services.GetService<IServiceScopeFactory().CreateScope();
var context =  scope.ServiceProvider.GetService<ApplicationDbContext();

Ref. https://github.com/dotnet/aspnetcore/issues/14424

Pinguid answered 27/9, 2021 at 19:48 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Feathered

© 2022 - 2024 — McMap. All rights reserved.