Skip to content

Instantly share code, notes, and snippets.

@mirmostafa
Last active February 17, 2024 11:38
Show Gist options
  • Save mirmostafa/a5afa8c44f579417c7210f5df22951a4 to your computer and use it in GitHub Desktop.
Save mirmostafa/a5afa8c44f579417c7210f5df22951a4 to your computer and use it in GitHub Desktop.
Add IoC and Mock DB to xunit test
public static void ConfigureServices(IServiceCollection services)
{
services.AddUnitTestServices();
var result = services.BuildServiceProvider();
DI.Initialize(result);
InitializeDatabase();
}
private static void InitializeDatabase()
{
var db = DI.GetService<InfraWriteDbContext>();
_ = db.Database.EnsureDeleted();
_ = db.Database.EnsureCreated();
// Initial Seed Database
_ = db.SaveChanges();
}
internal static class ServiceCollectionExtensions
{
public static void AddUnitTestServices(this IServiceCollection services)
{
var inMemoryDatabaseRoot = new InMemoryDatabaseRoot();
_ = services
.AddDbContext<InfraWriteDbContext>(options => options.UseInMemoryDatabase("MesInfra", inMemoryDatabaseRoot)
.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning)))
.AddDbContext<InfraReadDbContext>(options => options.UseInMemoryDatabase("MesInfra", inMemoryDatabaseRoot));
}
}
<ItemGroup>
<PackageReference Include="Xunit.DependencyInjection" Version="8.9.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.1" />
</ItemGroup>
{
"appDomain": true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment