之前用的是 xUnit.net ,在集成测试中是这样 seed data 的
public class MsgWebApplicationFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.Configure(app =>
{
var context = app.ApplicationServices.GetRequiredService<MessageContext>();
context.SeedDataAsync().Wait();
});
}
}
现在迁移到 TUnit,有没有更好的方法进行 seed data?
TUnit 中可以在 class 或 assembly 级别使用 [BeforeAll] 做 seed。对于 WebApplicationFactory 场景,推荐在测试类的 [BeforeAll] 里直接调用 seed 方法并等待完成;或者抽取为共享的 [ModuleInitializer] 方法让所有集成测试复用。如果需要每个测试后清理,配合 [AfterAll] 或 IAsyncDisposable 处理即