.NET Core集成测试解决作用域服务问题

8

我的集成测试很简单。我调用创建应用程序API,然后检查应用程序记录是否正确插入。

这是我的CustomWebApplicationFactory:

public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<Startup>
{
    public CustomWebApplicationFactory()
    {
        Configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile($"appsettings.{CustomEnvironments.IntegrationTests}.json", optional: true)
            .AddEnvironmentVariables()
            .Build();

        Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration).CreateLogger();

        Log.Information("Starting integration tests");
    }

    protected override IHostBuilder CreateHostBuilder() =>
         base.CreateHostBuilder()
        .UseEnvironment(CustomEnvironments.IntegrationTests)
        .UseSerilog();  
}

以下是我的ApplicationControllerTests类:

public class ApplicationControllerTests : IClassFixture<CustomWebApplicationFactory<Startup>>
{
    private readonly HttpClient _client;
    private readonly MyDbContext _db;
    private readonly CustomWebApplicationFactory<Startup> _factory;

   public ApplicationControllerTests(
        CustomWebApplicationFactory<Startup> factory)
    {
        _factory = factory;
        _client = factory.CreateClient();
        _db = factory.Services.GetRequiredService<MyDbContext>();
    }

    [Fact]
    public async Task CreateApplication_WhenCalled_ShouldReturnSuccess()
    {
        var request = new CreateApplicationRequest
                     {
                       Name = "App1"
                     }
                              

        var response = await _client.PostAsync("/api/v1/Application/CreateApplicationForLive", request.ToJsonStringContent());

        response.EnsureSuccess();

        var applicationId = await response.Deserialize<Guid>();

        var application = _db.Set<Application>().Find(applicationId);
        Assert.Equal(request.Name, application.Name);
    }
}

当我试图解析MyDbContext范围服务 _db = factory.Services.GetRequiredService<MyDbContext>(); 时,出现以下错误:'Cannot resolve scoped service from root provider.' 从WebApplicationFactory获取范围服务的正确方法是什么? 我在文档中没有找到任何示例。 asp.net core中的集成测试
1个回答

15
在WebApplicationFactory中解决作用域服务的正确方法是创建作用域:
var scope = factory.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
_db = scope.ServiceProvider.GetRequiredService<MyDbContext>();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接