How to isolate EF InMemory database per XUnit test

后端 未结 2 1483
无人共我
无人共我 2020-12-14 06:43

I am trying use InMemory EF7 database for my xunit repository test.

But my problem is that when i try to Dispose the created context the in memory db persist. It me

2条回答
  •  甜味超标
    2020-12-14 07:04

    From the documentation,

    Typically, EF creates a single IServiceProvider for all contexts of a given type in an AppDomain - meaning all context instances share the same InMemory database instance. By allowing one to be passed in, you can control the scope of the InMemory database.

    Instead of making the test class disposable and trying to dispose the data context that way, create a new one for each test:

    private static DbContextOptions CreateNewContextOptions()
    {
        // Create a fresh service provider, and therefore a fresh 
        // InMemory database instance.
        var serviceProvider = new ServiceCollection()
            .AddEntityFrameworkInMemoryDatabase()
            .BuildServiceProvider();
    
        // Create a new options instance telling the context to use an
        // InMemory database and the new service provider.
        var builder = new DbContextOptionsBuilder();
        builder.UseInMemoryDatabase()
               .UseInternalServiceProvider(serviceProvider);
    
        return builder.Options;
    }
    

    Then, in each test, new up a data context using this method:

    using (var context = new DatabaseContext(CreateNewContextOptions()))
    {
        // Do all of your data access and assertions in here
    }
    

    This approach should get you a squeaky-clean in-memory database for each test.

提交回复
热议问题