在 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);
}

我收到此错误:



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

最佳答案

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

首先摆脱 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

关于c# - 在 IntegrationTests 中实例化 DbContext,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46253464/

10-17 02:31