How to set up the DbContext in xUnit test project properly?

c# entity-framework entity-framework-core xunit

Question

I have the following code to set up DBContext in the .Net core 2.0 console program and it's injected to the constructor of the main application class.

    IConfigurationRoot configuration = GetConfiguration();
    services.AddSingleton(configuration);
    Conn = configuration.GetConnectionString("ConnStr1");

    services.AddDbContext<MyDbContext>(o => o.UseSqlServer(Conn));

Now I created a xUnit test class and need to initialize the same DbContext for testing.

    context = new MyDbContext(new DbContextOptions<MyDbContext>());

It gets the error of the parameter connectionString cannot be null. How to set up the DbContext in test project properly?

1
7
9/14/2017 8:59:11 PM

Accepted Answer

I found a way to do it.

var dbOption = new DbContextOptionsBuilder<MyDbContext>()
    .UseSqlServer("....")
    .Options;
4
9/14/2017 9:09:12 PM

Popular Answer

The George Alexandria's solutions work for me:

var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionsBuilder.UseInMemoryDatabase(); 
var context = new MyDbContext(optionsBuilder.Options);


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