Instantiate a DbContext in IntegrationTests

.net-core asp.net-core c# entity-framework entity-framework-core

Question

In the WebApi (.NET Core 2.0 + EF Core) project in Startup.cs

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

    services.AddMvc();
}

The Context:

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

    public MyContext()
    {
    }

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

No problem when I call the WebApi.

But in my integration test, I'd like do this :

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

    var service = new MyService(context);

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

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

I get this error :

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider

How can I instantiate the context and specify the connectionstring to use?

1
3
9/16/2017 12:01:08 PM

Accepted Answer

The context still needs to get the connection string and configuration while your default constructor bypasses all of that.

First get rid of the default constructor in your Db context

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

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

Next update the test to take advantage of the already provided configuration functionality

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

Reference Configuring a DbContext: Configuring DbContextOptions

6
9/16/2017 12:01:47 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow