在集成测试中访问内存dbcontext

时间:2019-03-07 22:41:25

标签: testing asp.net-core integration-testing

如何在集成测试中访问内存数据库的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播种的表中的数据

但不确定要放置什么选项

1 个答案:

答案 0 :(得分:2)

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

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