Entity Framework Core InMemory 数据库测试在并行运行时会中断

Sup*_*JMN 5 .net c# testing entity-framework entity-framework-core

运行所有测试时,我最终收到错误消息:

“已添加具有相同密钥的项目。密钥:125”

当每个测试单独运行时,这不会发生。

有趣的是,每个测试都使用不同的 DbName,以避免任何冲突:

[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);
}
Run Code Online (Sandbox Code Playgroud)

这真的很奇怪,因为当我单独运行测试时,它们是绿色的!当我同时运行它们时,有些最终会失败。

注意:我使用的是 Visual Studio 2017 中的集成 MSTest。

Bea*_*art 7

遇到同样的问题,解决方案是为每个测试类使用不同的数据库名称。这样做时,您会在测试类中获得相同的 dbcontext,但同时运行所有测试时不会与不同线程发生冲突。

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

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

       _inMemoryContext = new YourDbContext(_options);
Run Code Online (Sandbox Code Playgroud)