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