本文介绍了在集成测试中访问内存dbcontext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在集成测试中访问内存数据库的dbcontext?

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

我在这里遵循了以下代码: https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2#customize-webapplicationfactory

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
            });
    }

在此IndexPageTests中是否可以访问内存中的dbcontext?

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

我尝试过

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

我需要访问我以前从CustomWebApplicationFactory播种的表中的数据

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

但不确定要输入什么选项

but not sure what to put for the options

推荐答案

感谢Nikosi,这是我设法获得dbcontext的方法

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>();
}

这篇关于在集成测试中访问内存dbcontext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 20:56