.net core integration tests resolve scoped services
Asked Answered
U

1

9

My integration test is simple. I call to create application API and then check if application record is correctly inserted.

This is my 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();  
}

And this is my ApplicationControllerTests class:

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);
    }
}

But when I try to resolve MyDbContext scoped service _db = factory.Services.GetRequiredService<MyDbContext>(); I am getting the following error: 'Cannot resolve scoped service from root provider.'

What is the proper way to get scoped services from WebApplicationFactory? I could not find any example from documentation Integration tests in asp.net core

Unearthly answered 16/11, 2020 at 10:46 Comment(0)
U
16

Correct way to resolve scoped services in WebApplicationFactory is to create scope:

var scope = factory.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
_db = scope.ServiceProvider.GetRequiredService<MyDbContext>();
Unearthly answered 18/11, 2020 at 10:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.