运行所有测试时,我最终收到错误消息:
"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/