using Microsoft.EntityFrameworkCore; using global::BuildFlow.Shared.Domain.Common; namespace BuildFlow.Workflow.Tests; public static class TestDbFactory { /// 新建带审计模拟的 InMemory DbContext。 public static WorkflowDbContext Create() { var options = new DbContextOptionsBuilder() .UseInMemoryDatabase($"wf-test-{Guid.NewGuid()}") .Options; var db = new WorkflowDbContext(options); AttachAuditStub(db); return db; } /// 给已有 DbContext 挂上审计字段自动填充(供各测试 helper 复用)。 public static void AttachAuditStub(WorkflowDbContext db) { db.SavingChanges += (sender, _) => { if (sender is not DbContext ctx) return; foreach (var entry in ctx.ChangeTracker.Entries()) { if (entry.Entity is IAuditable a) { a.CreatedBy ??= "test"; a.UpdatedBy ??= "test"; } if (entry.Entity is IHasOperatorIP o) { o.OperatorIP ??= "127.0.0.1"; } } }; } }