实体框架核心InMemory数据库测试在并行运行时中断 [英] Entity Framework Core InMemory database tests break when run in parallel

查看:42
本文介绍了实体框架核心InMemory数据库测试在并行运行时中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When running all the test, I'm eventually getting errors saying:

已经添加了具有相同键的项.键:125"

"An item with the same key has already been added. Key: 125"

当每个测试单独运行时,不会发生这种情况.

This doesn't happen when each test is run separately.

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

The funny thing is that each test works with a different DbName, to avoid any conflict:

[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);
}

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

It's really strange, because when I run the tests individually, they are Green! and when I run them all at the same time, some eventually fail.

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

NOTE: I'm using the integrated MSTest from Visual Studio 2017.

推荐答案

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

Ran into the same issue, solution was to use different databaseName for each Test Class. When doing that you get the same dbcontext in the test class, but it will not collide with different threads when running all tests at once.

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

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

       _inMemoryContext = new YourDbContext(_options);

这篇关于实体框架核心InMemory数据库测试在并行运行时中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆