Backend/e-suite.Database.Audit/e-suite.Database.Audit.UnitTests/Helpers/TestDbContextFactory.cs
2026-01-20 21:50:10 +00:00

45 lines
1.3 KiB
C#

using System.Data.Common;
using eSuite.Core.Clock;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace e_suite.Database.Audit.UnitTests.Helpers;
public class TestDbContextFactory : IDisposable
{
//private const string _connectionString = "Data Source = InMemorySample; Mode=Memory;Cache=Shared";
private const string _connectionString = "DataSource=:memory:";
private DbConnection _connection = null!;
private DbContextOptions<TestDbContext> CreateOptions()
{
return new DbContextOptionsBuilder<TestDbContext>()
.UseSqlite(_connection).Options;
}
public TestDbContext CreateContext( IClock clock)
{
if (_connection == null)
{
_connection = new SqliteConnection(_connectionString);
_connection.Open();
var options = CreateOptions();
using var context = new TestDbContext(options, clock);
context.Database.EnsureCreated();
}
return new TestDbContext(CreateOptions(), clock);
}
public void Dispose()
{
if (_connection != null)
{
_connection.Dispose();
_connection = null!;
}
GC.SuppressFinalize(this);
}
}