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
ASP.NET Core has an extremely useful integration testing framework, in the form of the NuGet package Microsoft. AspNetCore. Mvc.
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.
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>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With