unit-testing - 替换 WebApplicationFactory 中的 DbContext 进行单元测试
问题描述
我需要替换 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
强制 EnsureCreatedOnModelCreating
用于 SQLite?是提取IMyDbContext
选项吗?我还能做些什么来解决这个问题?
解决方案
向服务容器注册 DbContext。打开 Startup.cs 并在 ConfigureServices 函数中,我们将使用 AddDbContext 扩展方法来添加我们的新 DbContext 并告诉它使用 SQLite 和我们的 appsettings.json 中的连接字符串。以下是完整的功能,前两行是我们添加的。
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ContactsDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers();
services.AddOpenApiDocument(document =>
document.PostProcess = d => d.Info.Title = "Contacts API");
}
推荐阅读
- arcgis - 边界框坐标
- c++ - 为什么我会为 SPOJ 上的 GSS1 问题的此代码获取 TLE?(使用段树)
- android - 您的应用未使用 AndroidX - Flutter 不允许我生成 apk
- xaml - 具有 Materialdesigninxaml 样式的按钮的中心边距定义
- python - 计算数据框中的日期列
- io - Ada.Text_IO.End_Of_File 缓冲副作用
- c# - 抄送电子邮件没有收到c#
- c++ - 为什么我的多线程并行求和函数的向量受限于线程数?
- python - 在 postgres 中将列数据类型从 VARCHAR 转换为 ARRAY(使用 Psycopg2)
- reference - 如何在 LibreOffice 中重新创建页面引用