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, 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()
?