【问题标题】:Instantiate a DbContext in IntegrationTests在 IntegrationTests 中实例化一个 DbContext
【发布时间】:2018-02-25 11:11:14
【问题描述】:

在 Startup.cs 中的 WebApi (.NET Core 2.0 + EF Core) 项目中

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContextPool<MyContext>(options =>
        options.UseSqlServer(_config["ConnectionStrings:MyConnectionString"]));

    services.AddMvc();
}

上下文:

public class MyContext : DbContext
{
    public MyContext(DbContextOptions<MyContext> options)
        : base(options)
    { }

    public MyContext()
    {
    }

    public DbSet<Employee> Employees { get; set; }
}

当我调用 WebApi 时没有问题。

但在我的集成测试中,我想这样做:

[Fact]
void TestMethod()
{
    var context = new MyContext();

    var service = new MyService(context);

    var result = service.GetAll();//Error here

    Assert.True(result.Count() > 0);
}

我收到此错误:

没有为此 DbContext 配置数据库提供程序。一种 可以通过覆盖 DbContext.OnConfiguring 来配置提供程序 方法或通过在应用程序服务提供者上使用 AddDbContext

如何实例化上下文并指定要使用的连接字符串?

【问题讨论】:

    标签: c# entity-framework asp.net-core .net-core entity-framework-core


    【解决方案1】:

    上下文仍然需要获取连接字符串和配置,而您的默认构造函数会绕过所有这些。

    首先摆脱 Db 上下文中的默认构造函数

    public class MyContext : DbContext {
        public MyContext(DbContextOptions<MyContext> options)
            : base(options)
        { }
    
        public DbSet<Employee> Employees { get; set; }
    }
    

    接下来更新测试以利用已经提供的配置功能

    [Fact]
    void TestMethod() {
        //Arrange
        var optionsBuilder = new DbContextOptionsBuilder<MyContext>();
        optionsBuilder.UseSqlServer("connection string here");
    
        using (var context = new MyContext(optionsBuilder.Options)) {
            var service = new MyService(context);
    
            //Act
            var result = service.GetAll();//Error here
    
            //Assert
            Assert.True(result.Count() > 0);
        }
    }
    

    参考Configuring a DbContext: Configuring DbContextOptions

    【讨论】:

      猜你喜欢
      • 2018-11-20
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 1970-01-01
      相关资源
      最近更新 更多