dramaling-vocab-learning/backend/DramaLing.Api.Tests/TestBase.cs

76 lines
2.0 KiB
C#

using DramaLing.Api.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Moq;
namespace DramaLing.Api.Tests;
/// <summary>
/// 測試基底類別,提供共用的測試設定和工具
/// </summary>
public abstract class TestBase : IDisposable
{
protected DramaLingDbContext DbContext { get; private set; }
protected IMemoryCache MemoryCache { get; private set; }
protected Mock<ILogger<T>> CreateMockLogger<T>() => new Mock<ILogger<T>>();
protected TestBase()
{
SetupDatabase();
SetupCache();
}
/// <summary>
/// 設定 In-Memory 資料庫
/// </summary>
private void SetupDatabase()
{
var options = new DbContextOptionsBuilder<DramaLingDbContext>()
.UseInMemoryDatabase(databaseName: $"TestDb_{Guid.NewGuid()}")
.Options;
DbContext = new DramaLingDbContext(options);
DbContext.Database.EnsureCreated();
}
/// <summary>
/// 設定記憶體快取
/// </summary>
private void SetupCache()
{
MemoryCache = new MemoryCache(new MemoryCacheOptions
{
SizeLimit = 100 // 限制測試時的快取大小
});
}
/// <summary>
/// 清理測試資料
/// </summary>
protected void ClearDatabase()
{
DbContext.OptionsVocabularies.RemoveRange(DbContext.OptionsVocabularies);
DbContext.Flashcards.RemoveRange(DbContext.Flashcards);
DbContext.Users.RemoveRange(DbContext.Users);
DbContext.SaveChanges();
}
/// <summary>
/// 清理快取
/// </summary>
protected void ClearCache()
{
if (MemoryCache is MemoryCache mc)
{
mc.Compact(1.0); // 清空所有快取項目
}
}
public virtual void Dispose()
{
DbContext?.Dispose();
MemoryCache?.Dispose();
GC.SuppressFinalize(this);
}
}