System.AggregateException: 'One or more hosted services failed to stop. (The operation was canceled.)'

Viewed 66

I am writing integration test using XUnit and my web api code is also in C# NET 6 and EF Core.

When I debug it, it can reach the web api and its service layer. But when it reaches EF Core context query example private Message? GetMessage() => _myContext.Messages.OrderBy(m => m.CreatedUtc).FirstOrDefault();, it breaks at Program.cs.

enter image description here

This is the code for TestingWebAppFactory class

public class TestingWebAppFactory<TEntryPoint> : WebApplicationFactory<Program> where TEntryPoint : Program
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =>
        {
            var descriptor = services.SingleOrDefault(
                d => d.ServiceType ==
                    typeof(DbContextOptions<MyContext>));

            if (descriptor != null)
                services.Remove(descriptor);

            services.AddDbContext<MyContext>(options =>
            {
                options.UseInMemoryDatabase("myinmemorydb");
            });

            var sp = services.BuildServiceProvider();
            using (var scope = sp.CreateScope())
            using (var appContext = scope.ServiceProvider.GetRequiredService<MyContext>())
            {
                try
                {
                    appContext.Database.EnsureCreated();
                }
                catch (Exception ex)
                {
                    //Log errors or do anything you think it's needed
                    throw;
                }
            }
        });
    }
}

and this is my code in Xunit

public class MyServiceTest : IClassFixture<TestingWebAppFactory<Program>>
{

    private readonly HttpClient _client;

    public MyServiceTest(TestingWebAppFactory<Program> factory)
    {
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task WhenAValidMessagePosted_ThenShouldReturn()
    {
        CancellationTokenSource source = new CancellationTokenSource();
        CancellationToken token = source.Token;
        source.CancelAfter(TimeSpan.FromSeconds(5));
        var response = await _client.GetAsync("https://localhost:xxxx/api/service/message/post?cronExpresson=0");
    }
}
0 Answers
Related