Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core InMemory database tests break when run in parallel

When running all the test, I'm eventually getting errors saying:

"An item with the same key has already been added. Key: 125"

This doesn't happen when each test is run separately.

The funny thing is that each test works with a different DbName, to avoid any conflict:

[TestMethod]
public void Test1() 
{
    using (var context = CreateTestingContext()) 
    {
        ...
    }
}

[TestMethod]
public void Test2() 
{
    using (var context = CreateTestingContext()) 
    {
        ...
    }
}

protected static SGDTPContext CreateTestingContext([CallerMemberName] string dbName = "TestingDb")
{
    var builder = new DbContextOptionsBuilder<MyDbContext>().UseInMemoryDatabase(dbName);
    return new MyDbContext(builder.Options);
}

It's really strange, because when I run the tests individually, they are Green! and when I run them all at the same time, some eventually fail.

NOTE: I'm using the integrated MSTest from Visual Studio 2017.

like image 611
SuperJMN Avatar asked Oct 28 '22 23:10

SuperJMN


1 Answers

Ran into the same issue, solution was to use different databaseName for each Test Class. When doing that you get the same dbcontext in the test class, but it will not collide with different threads when running all tests at once.

        protected readonly YourDbContext _inMemoryContext;
        protected readonly DbContextOptions<YourDbContext> _options;

        _options = new DbContextOptionsBuilder<YourDbContext>().UseInMemoryDatabase(databaseName: "WhateverNameforClassScope").Options;

       _inMemoryContext = new YourDbContext(_options);
like image 189
BearOakheart Avatar answered Nov 15 '22 05:11

BearOakheart