Instantiate a DbContext in IntegrationTests

Viewed 990

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 Answers
Related