Search code examples
xunitdnxentity-framework-core

How to properly initialize EF7 for xunit tests run with xunit.runner.dnx


I have a DNX unit test assembly where I'm testing code that uses EF7.

In a web app, I have the Startup class where I can provide a ConfigureServices(IServiceCollection services) method and initialize like so:

public void ConfigureServices(IServiceCollection services)
{
    services.AddEntityFramework()
        .AddSqlServer()
        .AddDbContext<RadarDbContext>(options =>
            options.UseSqlServer(
            Configuration["Data:DefaultConnection:ConnectionString"]));
}

Where is the equivalent "hook" for an xunit test running under DNX?


Solution

  • The DNX runner for Xunit never calls Startup.cs. The "hook" you are looking for is either a class fixture or your test class constructor. (See https://xunit.github.io/docs/shared-context.html)

    How you choose to initialize EF from there is up to you. You could use dependency injection and follow the .AddDbContext() pattern above or you could initialize your DbContext directly. (see https://github.com/aspnet/EntityFramework/wiki/Configuring-a-DbContext which is slightly outdated)