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, Task
1 responseTask, Boolean usingResponseHeadersRead, CancellationTokenSource linkedCTS, Func
4 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