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

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

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

"An item with the same key has already been added. Key: 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。

最佳答案

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

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

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

       _inMemoryContext = new YourDbContext(_options);

关于c# - Entity Framework Core InMemory 数据库测试在并行运行时会中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47335920/

相关文章:

c# - 用于消费者SDK的Skype(Skype4COM)更改了蓝牙设备的默认音频输出和输入C#

c# - 通过过滤将列表<>添加到另一个列表<>

c# - 无法从 'System.Threading.Tasks.Task' 转换为 'System.Collections.Generic.Dictionary<string,string>'

c# - 业务逻辑层设计

c# - Linq Entity Framework 泛型过滤方法

c# - 如何在没有类实例的情况下获取EF动态代理类的类型

c# - 如何在 C# 中使用 trim() 来消除更多空格?

c# - linq 到实体 : linq query performance optimization

.net - Entity Framework 子查询

c# - 指示命令行激活已成功完成UWP