Files
TakeoutSaaS.AdminApi/tests/TakeoutSaaS.Integration.Tests/Fixtures/SqliteTestDatabase.cs

59 lines
1.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using TakeoutSaaS.Infrastructure.App.Persistence;
namespace TakeoutSaaS.Integration.Tests.Fixtures;
/// <summary>
/// 集成测试用 SQLite 内存数据库(业务主库)。
/// </summary>
public sealed class SqliteTestDatabase : IDisposable
{
private readonly SqliteConnection _connection;
private readonly TestIdGenerator _idGenerator = new();
private bool _initialized;
public SqliteTestDatabase()
{
_connection = new SqliteConnection("Filename=:memory:");
_connection.Open();
Options = new DbContextOptionsBuilder<TakeoutAdminDbContext>()
.UseSqlite(_connection)
.EnableSensitiveDataLogging()
.Options;
}
public DbContextOptions<TakeoutAdminDbContext> Options { get; }
public TakeoutAdminDbContext CreateContext(long tenantId, long userId = 0)
{
EnsureCreated();
// 1. AdminApi 不使用租户上下文tenantId 参数仅用于兼容测试调用方签名
_ = tenantId;
// 2. (空行后) 按需注入当前用户与 ID 生成器
return new TakeoutAdminDbContext(
Options,
userId == 0 ? null : new TestCurrentUserAccessor(userId),
_idGenerator);
}
public void EnsureCreated()
{
if (_initialized)
{
return;
}
// 1. 创建并初始化数据库结构
using var context = new TakeoutAdminDbContext(Options, idGenerator: _idGenerator);
context.Database.EnsureCreated();
_initialized = true;
}
public void Dispose()
{
_connection.Dispose();
}
}