Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 917
ca9163d9 Avatar asked Sep 14 '17 20:09

ca9163d9


3 Answers

The George Alexandria's solutions work for me:

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

The UseInMemoryDatabase extension method is included in Microsoft.EntityFrameworkCore.InMemory

like image 125
re_al_ Avatar answered Oct 10 '22 01:10

re_al_


I found a way to do it.

var dbOption = new DbContextOptionsBuilder<MyDbContext>()
    .UseSqlServer("....")
    .Options;
like image 23
ca9163d9 Avatar answered Oct 10 '22 01:10

ca9163d9


EF 2.0 requires that all in-memory database are named, so be sure to name it like so:

var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionsBuilder.UseInMemoryDatabase("MyInMemoryDatabseName"); 
var context = new MyDbContext(optionsBuilder.Options);
like image 26
user3142554 Avatar answered Oct 10 '22 01:10

user3142554