【发布时间】:2021-08-24 19:49:33
【问题描述】:
我需要在 WebApplicationFactory 中替换上下文。我有 MyDbContext,我想用 SQLite 上下文替换它以进行测试。
替换部分工作正常
.ConfigureServices(services =>
{
// Remove the app's ApplicationDbContext registration.
var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<MyDbContext>));
if (descriptor != null)
{
services.Remove(descriptor);
}
services.AddDbContext<MyDbContext>(builder =>
{
builder.UseSqlite(CreateInMemoryDatabase());
});
});
但是因为我在测试中从 Npgsql 迁移到 SQLite,所以我需要覆盖 OnModelCreating 中的一些默认值。我创建了一个新的数据库上下文类
public class MySqlLiteDbContext: MyDbContext
{
public MySqlLiteDbContext(DbContextOptions<MyDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Record>()
.Property(b => b.DateCreated)
.HasDefaultValueSql("(datetime('now'))");
...
}
}
有没有办法注入 MySqlLiteDbContext 而不是 MyDbContext 来强制 EnsureCreated 使用 OnModelCreating 用于 SQLite?提取IMyDbContext 是一种选择吗?我还能做些什么来解决这个问题?
【问题讨论】:
标签: unit-testing asp.net-core .net-core entity-framework-core