Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing With Entity Framework 7, Test fails sometimes?

I have a bunch of test where I use the new UseInMemory function in EF7. When I run them all some of them fail. When I run them single they all pass. My best guess it is a conflict in EF7 because of the fact that every test runs in its own thread and they all kind of using the same DbContext class. Here one of my Tests:

    [Fact]
    public void Index()
    {

        DbContextOptionsBuilder<DatabaseContext> optionsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
        optionsBuilder.UseInMemoryDatabase();
        db = new DatabaseContext(optionsBuilder.Options);
        AdminController controller = new AdminController(db);

        var result = controller.Index() as ViewResult;
        Assert.Equal("Index", result.ViewName);
    }

I remake the dbContext object in every test but it seem not to make any different.

Would be greatful for any input. Thanks :)

like image 971
Sknecht Avatar asked Feb 11 '26 16:02

Sknecht


1 Answers

The problem is, that the memory storage in InMemoryDatabase is registered as Singleton so you actually share the data between DbContexts even you think you don't.

You have to create your DbContexts like this:

public abstract class UnitTestsBase
{
    protected static T GetNewDbContext<T>() where T : DbContext
    {
        var services = new ServiceCollection();

        services
            .AddEntityFramework()
            .AddInMemoryDatabase()
            .AddDbContext<T>(options => options.UseInMemoryDatabase());

        var serviceProvider = services.BuildServiceProvider();

        var dbContext = serviceProvider.GetRequiredService<T>();

        dbContext.Database.EnsureDeleted();

        return dbContext;
    }
}


var newTestDbContext = GetNewDbContext<TestDbContext>()
like image 195
Skorunka František Avatar answered Feb 15 '26 15:02

Skorunka František



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!