实体框架核心内存数据库测试在并行运行时中断



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

"已添加具有相同键的项目。按键: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。

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

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

最新更新