在IntegrationTests中实例化DbContext

Kri*_*s-I 3 c# entity-framework entity-framework-core .net-core asp.net-core

在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();
}
Run Code Online (Sandbox Code Playgroud)

上下文:

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

    public MyContext()
    {
    }

    public DbSet<Employee> Employees { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我打电话给WebApi时没问题.

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

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

    var service = new MyService(context);

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

    Assert.True(result.Count() > 0);
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

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

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

Nko*_*osi 6

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

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

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

    public DbSet<Employee> Employees { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)

参考配置DbContext:配置DbContextOptions