Using AspNetCore.TestHost with EntityFrameworkCore.InMemory losing data

358 views Asked by At

I'm trying to write an integration test for a small GraphQL server I have using graphql-dotnet. The server is working fine when I use my web application.

To run the integration test, I'm attempting to use Microsoft.AspNetCore.TestHost to configure the server and send the POST request. I'm also trying to use Microsoft.EntityFrameworkCore.InMemory to use an in-memory database rather than a "real" database running locally.

I have a TestStartUp.cs file that sets up the in-memory database and attempts to save a single record:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddDbContext<MyDbContext>(options =>
        options.UseInMemoryDatabase()
    );

    ...
}

public void Configure(
        IApplicationBuilder app, 
        IHostingEnvironment env,
        MyDbContext myDbContext)
{
    myDbContext.Categories.Add(new Category {Id = 1, Name = "Category 1" });
    myDbContext.SaveChanges();
    app.UseMvc();
}

I've printed out the contents of the database after calling SaveChanges() and confirmed that the object is being saved. However, when my repository object tries to retrieve all Categories in the injected MyDbContext object, it shows that no Categories exist.

I've tried various configurations to no avail. Using a database that isn't in memory works fine, so I'm sure there's something I'm missing. It's driving me mad, so any assistance would be very appreciated!

1

There are 1 answers

0
Dawid Rutkowski On

In order to use InMemoryDatabase in few places, you need to provide the same database options each time (use the same database). Take a look bellow:

    protected DbContextOptions<BackofficeContext> GetDbContextOptions()
    {
        return new DbContextOptionsBuilder<BackofficeContext>().UseInMemoryDatabase(NAME_OF_YOUR_IN_MEMORY_DATABASE).Options;
    }

And then you can do something like that:

var databaseOptions = GetDbContextOptions();

using (var context = new MyContext(databaseOptions))
{
    //Add some data to the database
    context.SaveChanges();
}

using (var context = new MyContext(databaseOptions))
{
    //Recieve data from the database
}