在集成测试中访问内存 dbcontext

rak*_*los 7 testing integration-testing asp.net-core

如何在集成测试中访问内存数据库的 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
            });
    }
Run Code Online (Sandbox Code Playgroud)

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

我试过了

 using (var context = new ApplicationDbContext(???))
Run Code Online (Sandbox Code Playgroud)

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

但不确定该选项的内容

rak*_*los 12

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

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

  • 添加 using `using Microsoft.Extensions.DependencyInjection;` 以便获得 `GetService&lt;T&gt;` 和 `GetRequiredService&lt;T&gt;` 方法 (4认同)
  • 我必须在 .NET 6 中使用 `_factory.Services.GetService&lt;IServiceScopeFactory&gt;()`。 (2认同)