如何正确设置xUnit测试项目中的DbContext?

问题描述 投票:4回答:2

我有以下代码在.Net core 2.0控制台程序中设置DBContext,它被注入到主应用程序类的构造函数中。

    IConfigurationRoot configuration = GetConfiguration();
    services.AddSingleton(configuration);
    Conn = configuration.GetConnectionString("ConnStr1");

    services.AddDbContext<MyDbContext>(o => o.UseSqlServer(Conn));

现在我创建了一个xUnit测试类,需要初始化相同的DbContext进行测试。

    context = new MyDbContext(new DbContextOptions<MyDbContext>());

它得到参数connectionString的错误不能为null。如何正确设置测试项目中的DbContext?

c# entity-framework entity-framework-core xunit
2个回答
4
投票

我找到了办法。

var dbOption = new DbContextOptionsBuilder<MyDbContext>()
    .UseSqlServer("....")
    .Options;

4
投票

George Alexandria的解决方案适合我:

var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionsBuilder.UseInMemoryDatabase(); 
var context = new MyDbContext(optionsBuilder.Options);
© www.soinside.com 2019 - 2024. All rights reserved.