【问题标题】:Access in memory dbcontext in integration test在集成测试中访问内存 dbcontext
【发布时间】:2019-03-07 22:41:24
【问题描述】:

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

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

【问题讨论】:

  • 您必须通过主机的服务提供商解决它。 factory.Server.Host.Services.GetService&lt;ApplicationDbContext&gt;()
  • @Nkosi,这给出了错误:无法从根提供程序解析范围服务'ApplicationDbContext'。
  • @Nikosi,谢谢你为我指明了正确的方向......必须首先创建范围 _factory.Server.Host.Services.GetService();
  • 很高兴为您提供帮助。您应该将其添加为自己的答案,以便其他人受益。

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


【解决方案1】:

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

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

【讨论】:

  • 添加使用 using Microsoft.Extensions.DependencyInjection; 以便获得 GetService&lt;T&gt;GetRequiredService&lt;T&gt; 方法
【解决方案2】:

以下对我有用,因为它没有引发异常:

var scope = factory.Services.GetService<IServiceScopeFactory().CreateScope();
var context =  scope.ServiceProvider.GetService<ApplicationDbContext();

参考。 https://github.com/dotnet/aspnetcore/issues/14424

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多