using Marathon.Infrastructure.Persistence; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; namespace Marathon.Infrastructure.Tests.Persistence; /// /// Shared in-memory SQLite fixture for persistence tests. /// Uses a named in-memory database with a shared cache connection so the schema /// created in EnsureCreated() is visible across the lifetime of each test. /// public sealed class InMemoryDbFixture : IDisposable { private readonly SqliteConnection _keepAliveConnection; public MarathonDbContext DbContext { get; } public InMemoryDbFixture() { // Each fixture instance gets its own in-memory database so xUnit's per-test // isolation isn't violated when tests run in parallel within a class // (the previous shared "marathon_tests" name caused state contamination). var dbName = $"marathon_tests_{Guid.NewGuid():N}"; var connectionString = $"Data Source={dbName};Mode=Memory;Cache=Shared"; // Keep a single connection open so the named in-memory DB lives until the // fixture is disposed. _keepAliveConnection = new SqliteConnection(connectionString); _keepAliveConnection.Open(); var options = new DbContextOptionsBuilder() .UseSqlite(connectionString) .Options; DbContext = new MarathonDbContext(options); DbContext.Database.EnsureCreated(); } public void Dispose() { DbContext.Dispose(); _keepAliveConnection.Dispose(); } }