Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12141

Test fails with connection resolved from provider of AddDbContext but succeeds with one resolved from services of ConfigureTestServices()

$
0
0

I am following this official tutorial.Here is my code:

public sealed class CustomWebApplicationFactory : WebApplicationFactory<Program>{    private DbConnection _connection = null!; // <=========== B    protected override void ConfigureWebHost(IWebHostBuilder builder)    {        base.ConfigureWebHost(builder);        builder.ConfigureTestServices(services =>        {            services.RemoveAll(typeof(DbContextOptions<AppDbContext>));            services.RemoveAll(typeof(DbConnection));            services.AddSingleton<DbConnection>(provider =>            {                var connection = new SqliteConnection("DataSource=:memory:");                connection.Open();                return connection;            });            services.AddDbContext<AppDbContext>((provider, options) =>            {                //options.UseSqlite(provider.GetRequiredService<DbConnection>()); // <=========== A                options.UseSqlite(_connection); // <=========== B            });            var provider = services.BuildServiceProvider();            _connection = provider.GetRequiredService<DbConnection>(); // <=========== B        });    }}

There are two options:

  • option A is based on the official tutorial but it produces error

    Message: System.Net.Http.HttpRequestException : Response status code does not indicate success: 500 (Internal Server Error).Stack Trace: HttpResponseMessage.EnsureSuccessStatusCode()HttpClientJsonExtensions.g__Core|12_0[TValue,TJsonOptions](HttpClient client, Task1 responseTask, Boolean usingResponseHeadersRead, CancellationTokenSource linkedCTS, Func4 deserializeMethod, TJsonOptions jsonOptions, CancellationToken cancellationToken)Gets.Should_return_ArrayOfUsers() line 10

  • option B uses a field and it works.

What am I missing here? Why can't we use SqliteConnection obtained from provider of AddDbContext()?

Edit 1:

[Fact]public async Task Should_return_ArrayOfUsers(){    var content = await _http.GetFromJsonAsync<User[]>("users");    Assert.Equal(4, content!.Length);}

Edit 2:

A minimal github repo to reproduce the issue: https://github.com/ilcgf/bugreport/tree/main


Viewing all articles
Browse latest Browse all 12141

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>