Last active
February 17, 2024 11:38
-
-
Save mirmostafa/a5afa8c44f579417c7210f5df22951a4 to your computer and use it in GitHub Desktop.
Add IoC and Mock DB to xunit test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<ItemGroup> | |
<PackageReference Include="Xunit.DependencyInjection" Version="8.9.1" /> | |
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.1" /> | |
</ItemGroup> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"appDomain": true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment