Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 549
Kris-I Avatar asked Oct 15 '25 22:10

Kris-I


1 Answers

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

like image 141
Nkosi Avatar answered Oct 18 '25 12:10

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!