如何在 xUnit 测试项目中正确设置 DbContext?
How to set up the DbContext in xUnit test project properly?
我有以下代码在 .Net core 2.0 控制台程序中设置 DBContext,它被注入到主应用程序的构造函数中 class。
IConfigurationRoot configuration = GetConfiguration();
services.AddSingleton(configuration);
Conn = configuration.GetConnectionString("ConnStr1");
services.AddDbContext<MyDbContext>(o => o.UseSqlServer(Conn));
现在我创建了一个 xUnit 测试 class 并且需要初始化相同的 DbContext 进行测试。
context = new MyDbContext(new DbContextOptions<MyDbContext>());
得到参数connectionString
不能为空的错误。如何正确设置测试项目中的 DbContext?
我找到了方法。
var dbOption = new DbContextOptionsBuilder<MyDbContext>()
.UseSqlServer("....")
.Options;
George Alexandria 的解决方案对我有用:
var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionsBuilder.UseInMemoryDatabase();
var context = new MyDbContext(optionsBuilder.Options);
UseInMemoryDatabase
扩展方法包含在Microsoft.EntityFrameworkCore.InMemory
中
EF 2.0 要求所有内存数据库都命名,所以一定要这样命名:
var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionsBuilder.UseInMemoryDatabase("MyInMemoryDatabseName");
var context = new MyDbContext(optionsBuilder.Options);
我有以下代码在 .Net core 2.0 控制台程序中设置 DBContext,它被注入到主应用程序的构造函数中 class。
IConfigurationRoot configuration = GetConfiguration();
services.AddSingleton(configuration);
Conn = configuration.GetConnectionString("ConnStr1");
services.AddDbContext<MyDbContext>(o => o.UseSqlServer(Conn));
现在我创建了一个 xUnit 测试 class 并且需要初始化相同的 DbContext 进行测试。
context = new MyDbContext(new DbContextOptions<MyDbContext>());
得到参数connectionString
不能为空的错误。如何正确设置测试项目中的 DbContext?
我找到了方法。
var dbOption = new DbContextOptionsBuilder<MyDbContext>()
.UseSqlServer("....")
.Options;
George Alexandria 的解决方案对我有用:
var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionsBuilder.UseInMemoryDatabase();
var context = new MyDbContext(optionsBuilder.Options);
UseInMemoryDatabase
扩展方法包含在Microsoft.EntityFrameworkCore.InMemory
EF 2.0 要求所有内存数据库都命名,所以一定要这样命名:
var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionsBuilder.UseInMemoryDatabase("MyInMemoryDatabseName");
var context = new MyDbContext(optionsBuilder.Options);