TheBoubou
TheBoubou

Reputation: 19933

Instantiate a DbContext in IntegrationTests

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?

Upvotes: 4

Views: 1207

Answers (1)

Nkosi
Nkosi

Reputation: 247571

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

Upvotes: 6

Related Questions