I am using CustomWebApplicationFactory to overide DbContextFactory to use an SQLite DB in integration test –
public class CustomWebApplicationFactory<TStartup>
: WebApplicationFactory<TStartup> where TStartup : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
// Remove the app's ApplicationDbContext registration.
removeService(services, typeof(DbContextOptions<PimsDbContext>));
removeService(services, typeof(IDbContextFactory<PimsDbContext>));
// Use in-memory SQLite database for testing.
// Create single connection for all DbContext instances, as a new SQLite in-memory database is created for each connection.
services.AddSingleton<DbConnection>(container =>
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
Console.WriteLine($"Connection address dbcontextfactory: {connection.GetHashCode()}");
return connection;
});
// Override DB context in Program.cs with SQLite in-memory database
services.AddDbContextFactory<PimsDbContext>((container, options) =>
{
var connection = container.GetRequiredService<DbConnection>();
options.UseSqlite(connection);
}, ServiceLifetime.Singleton);
services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
// Build the service provider.
var sp = services.BuildServiceProvider();
var dbContextFactory = sp.GetRequiredService<IDbContextFactory<PimsDbContext>>();
var db = dbContextFactory.CreateDbContext();
// Ensure the database is created.
db.Database.EnsureCreated();
SeedData(db);
});
}
But when I run the test, I observed that application is using a different instance of DbContextFactory than the one injected in ConfigureServices, due to which the seeded data is not present in that Dbcontext while running the test.
Test –
public class ControllerIntegrationTest
{
private CustomWebApplicationFactory<Program> _factory;
private HttpClient _client;
[SetUp]
public void SetUp()
{
_factory = new CustomWebApplicationFactory<Program>();
_client = _factory.CreateClient();
}
//... Test methods calling controller endpoint
}
Any idea why application is not using the same singleton DbContextFactory?