Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access in memory dbcontext in integration test

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

I have followed the code here: https://docs.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

like image 440
raklos Avatar asked Mar 07 '19 22:03

raklos


People also ask

Can Nunit be used for integration testing?

ASP.NET Core has an extremely useful integration testing framework, in the form of the NuGet package Microsoft. AspNetCore. Mvc.

Which package component can be added for integration testing of the .NET core API applications?

Mvc. Testing package is used to configure the test host and test server, the TestHost and TestServer packages don't require direct package references in the test app's project file or developer configuration in the test app.


1 Answers

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>();
}
like image 66
raklos Avatar answered Sep 21 '22 20:09

raklos