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

编程入门 行业动态 更新时间:2024-10-18 10:23:09
本文介绍了实体框架核心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数据库测试在并行运行时中断

本文发布于:2023-11-14 09:42:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586872.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实体   框架   核心   数据库   测试

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!