【问题标题】:Entity Framework Core InMemory database tests break when run in parallelEntity Framework Core InMemory 数据库测试在并行运行时中断
【发布时间】:2017-11-16 17:35:54
【问题描述】:

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

“已添加具有相同密钥的项目。密钥: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);
}

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

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

【问题讨论】:

  • VS 将在多个线程中运行测试,并且您的测试方法似乎在同一个数据库上运行。另请注意,来自多个文件的测试不一定会按顺序运行,即某些类的 Class 初始化程序可能会在前面的测试类的 Class Cleanup 方法之前运行。
  • @cassandrad [CallerMemberName] 属性告诉编译器注入调用者方法的名称,所以它是“Test1”和“Test2”。
  • 您也可以尝试使用随机 guid 作为数据库名称,以完全排除任何数据库名称冲突。
  • @SuperJMN 你能找到解决问题的方法吗?我也为此苦苦挣扎了好几天……:S
  • @mirind4 是的!看来我到底是用nameof错了。如果您将不同的名称传递给 dbName,它应该可以工作。

标签: c# .net entity-framework testing entity-framework-core


【解决方案1】:

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

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

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

       _inMemoryContext = new YourDbContext(_options);

【讨论】:

    猜你喜欢
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多