c# - 使用 EF Core 和内存中的 Sqliteprovider 对类进行单元测试 - 测试运行程序中的堆栈溢出错误
问题描述
我想为我的服务编写一个单元测试,并为此目的在内存中使用 Sqlite 数据库提供程序,但是,在尝试将一些实体添加到 DbContext 时,我在测试运行程序中遇到堆栈溢出错误。从 DbContext 读取时不会出现此问题。
测试代码:
public class DbBoardGameServiceTest : IDisposable
{
private readonly TestDbFactory _testDbFactory;
private readonly BoardGamesDbContext _dbContext;
private readonly Mock<IMapper> _mapperMock = new Mock<IMapper>();
private readonly DbBoardGameService _sut;
public DbBoardGameServiceTest()
{
_testDbFactory = new TestDbFactory();
_dbContext = _testDbFactory.CreateDbContext();
_sut = new DbBoardGameService(_dbContext, _mapperMock.Object);
}
[Fact(DisplayName = "All BoardGames from a database are returned after being mapped when service gets all board games")]
public void All_BoardGames_from_a_database_are_returned_when_after_being_mapped_service_gets_all_board_games()
{
_mapperMock.Setup(mock => mock.Map<BoardGameDto>(It.IsAny<Models.BoardGame>()))
.Returns<Models.BoardGame>(boardGame => DtoWithName(boardGame.Name));
_dbContext.BoardGames.AddRange(TestBoardGames); //this line causes stackoverflow
var games = _dbContext.BoardGames.ToArray(); // this line does not cause any errors
var actualBoardGames = _sut.GetAllBoardGames().ToArrayAsync().Result;
var expectedBoardGames = new[]
{
DtoWithName("Name1"),
DtoWithName("Name2"),
DtoWithName("Name3"),
DtoWithName("Name4"),
};
actualBoardGames.Should().BeEquivalentTo(expectedBoardGames);
}
private static Models.BoardGame[] TestBoardGames => new[]
{
new BoardGameBuilder().WithName("Name1").WithId(1).Build(),
new BoardGameBuilder().WithName("Name2").WithId(2).Build(),
new BoardGameBuilder().WithName("Name3").WithId(3).Build(),
new BoardGameBuilder().WithName("Name4").WithId(4).Build()
};
private static BoardGameDto DtoWithName(string name) => new BoardGameDto(0, name, 0, 0, 0);
public void Dispose() => _testDbFactory.Dispose();
}
我完全迷失了,我遇到了测试期间堆栈溢出可能是由循环依赖引起的信息,但我怀疑是这种情况。任何提示将不胜感激。
编辑:它在 Ubuntu 20.04 上失败,但在 macOS 上它工作正常。
解决方案
推荐阅读
- python - 将 JSON 格式结构化为指定的数据结构
- javascript - 我有一个图片库,我想在单击每个图片时使用模态打开每个图片
- c++ - 为什么 C++20 不允许在 requires-expression 中使用类型别名?
- sql - Cakephp 4.x 自定义查询
- javascript - 如何将变量设置为特定的语音通道 discord.js?
- html - 我的导航栏没有与我的英雄部分重叠
- python - 致命的 Python 错误:_Py_HashRandomization_Init:无法获取随机数来初始化 Python Python 运行时状态:预初始化
- google-cloud-storage - 在一个谷歌项目上生成的谷歌签名 URL 可以将存储桶对象上传到另一个谷歌项目吗?
- python - 根据类别将单个 JSON 拆分为多个 JSON,但未获取所有类别
- angular - Angular:Ngx-Translate 翻译服务不会动态更改语言