using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Novelly.Api.Data;
namespace Novelly.Api.Tests;
///
/// A throwaway SQLite database held in memory. Using real SQLite rather than the
/// in-memory provider means the tests exercise the same relational behaviour the app
/// ships with — cascade deletes, foreign keys and all.
///
///
/// NUnit reuses one fixture instance across every test in a class, so this must be built
/// in [SetUp] and disposed in [TearDown]. A field initialiser would share
/// one database for the whole class and let tests see each other's rows.
///
public class TestDatabase : IDisposable
{
private readonly SqliteConnection _connection;
public TestDatabase()
{
_connection = new SqliteConnection("Data Source=:memory:");
_connection.Open();
Context = CreateContext();
Context.Database.EnsureCreated();
}
public NovelDbContext Context { get; }
/// A second context over the same database, for asserting on persisted state.
public NovelDbContext CreateContext() =>
new(new DbContextOptionsBuilder().UseSqlite(_connection).Options);
public void Dispose()
{
Context.Dispose();
_connection.Dispose();
GC.SuppressFinalize(this);
}
}