59 lines
1.6 KiB
C#
59 lines
1.6 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using DramaLing.Api.Data;
|
|
|
|
namespace DramaLing.Api.Tests;
|
|
|
|
/// <summary>
|
|
/// 測試基類,提供通用的測試基礎設施
|
|
/// </summary>
|
|
public abstract class TestBase : IDisposable
|
|
{
|
|
protected readonly DramaLingDbContext DbContext;
|
|
protected readonly ServiceProvider ServiceProvider;
|
|
|
|
protected TestBase()
|
|
{
|
|
var services = new ServiceCollection();
|
|
ConfigureServices(services);
|
|
|
|
ServiceProvider = services.BuildServiceProvider();
|
|
DbContext = ServiceProvider.GetRequiredService<DramaLingDbContext>();
|
|
|
|
// 確保資料庫已建立
|
|
DbContext.Database.EnsureCreated();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 配置測試用服務
|
|
/// </summary>
|
|
protected virtual void ConfigureServices(IServiceCollection services)
|
|
{
|
|
// 使用 InMemory 資料庫
|
|
services.AddDbContext<DramaLingDbContext>(options =>
|
|
options.UseInMemoryDatabase(Guid.NewGuid().ToString()));
|
|
|
|
// 添加日誌記錄
|
|
services.AddLogging(builder => builder.AddConsole());
|
|
}
|
|
|
|
/// <summary>
|
|
/// 清理測試資料
|
|
/// </summary>
|
|
protected virtual async Task CleanupAsync()
|
|
{
|
|
if (DbContext != null)
|
|
{
|
|
await DbContext.Database.EnsureDeletedAsync();
|
|
}
|
|
}
|
|
|
|
public virtual void Dispose()
|
|
{
|
|
CleanupAsync().GetAwaiter().GetResult();
|
|
DbContext?.Dispose();
|
|
ServiceProvider?.Dispose();
|
|
GC.SuppressFinalize(this);
|
|
}
|
|
} |