首页 > 解决方案 > 在集成测试中访问内存 dbcontext

问题描述

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

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

并进行类似的测试:

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?

我努力了

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

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

但不确定要为选项添加什么

标签: testingasp.net-coreintegration-testing

解决方案


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

var scopeFactory = _factory.Server.Host.Services.GetService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope())
{
   var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
}

推荐阅读