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

3

21

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?

Mercaptide answered 14/9, 2017 at 20:59 Comment(1)
You just need to set options for it. As example this option are used to store db in the memory: var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>(); optionsBuilder.UseInMemoryDatabase(); var context = new MyDbContext(optionsBuilder.Options);Eyrir
M
14

I found a way to do it.

var dbOption = new DbContextOptionsBuilder<MyDbContext>()
    .UseSqlServer("....")
    .Options;
Mercaptide answered 14/9, 2017 at 21:9 Comment(1)
For others looking, the other solutions are slightly more complete in that they initialize the context too!Burnell
A
10

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

Airspeed answered 18/12, 2017 at 16:12 Comment(2)
For those who use this more complete method, don't forget to either use 'context.dispose()' or a using bracket i.e. using (var context = new MyDbContext(optionsBuilder.Options)){ // Your code here}.Saphead
Do you have configuration using fluent API? It seems the ModelBuilder is no available for the OnModelCreating(ModelBuilder modelBuilder) beucase it is supplied with DI from ASP.Net. Is there a way to supply the ModelBuilder for the DBContext in a testing project?Scalage
G
3

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);
Gertrudegertrudis answered 15/1, 2020 at 15:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.