During my startup of my Xunit tests I am defining dependency injection for my entity framework database context using a fake version with fake data called FakeMyDbContext.
public void ConfigureInMemoryDatabases(IServiceCollection services)
{
services.AddScoped(_ =>
{
var smtrOptions = new DbContextOptionsBuilder<MyDbContext>()
.UseInMemoryDatabase(databaseName: $"MyDb_{Guid.NewGuid()}")
.Options;
return new FakeMyDbContext(smtrOptions) as MyDbContext;
});
}
I have multiple tests that run for my service that consumes this database context, however only one ever runs. I have tracked down the issue being the following line in the Disposal of the FakeMyDbContext class:
public override void Dispose()
{
base.Dispose();
Database.EnsureDeleted();
}
If I remove the Database.EnsureDeleted(), then all the tests run. If I leave it in then only one test runs. I am not sure why this would happen as I see no errors and each context instance has a unique database name (guid appended).
The reason for my issue was that I was calling EnsureDeleted after disposing the Context.
The dispose method should look like this
public override void Dispose()
{
Database.EnsureDeleted();
base.Dispose();
}