【问题标题】:How to mock DbSet using xUnit and NSubstitute?如何使用 xUnit 和 NSubstitute 模拟 DbSet?
【发布时间】:2021-12-31 04:03:26
【问题描述】:

我开始使用 xUnit 和 NSubstitute 进行单元测试。我想模拟以下方法。

public async Task<DecorationModel> GetDecorationWithId(string userId, string decorationId)
{
    var decoration = await _db.Decorations
        .Include(d => d.BgImage)
        .FirstOrDefaultAsync(d => d.Id == decorationId);

    if (decoration == null || decoration.OwnerId != userId)
        return null;

    return new DecorationModel
    {
        Id = decoration.Id,
        Name = decoration.Name,
        // Other stuff
    };
}

我尝试过,但无法正常工作。我目前的测试类如下;

public class DecorationServiceTests
{
    private readonly DecorationService _subject;
    private readonly IAppDbContext _db = Substitute.For<IAppDbContext>();
    private readonly DbSet<Decoration> _decorationDbSet = Substitute.For<DbSet<Decoration>, IQueryable<Decoration>>();

    public DecorationServiceTests()
    {
        _subject = new DecorationService(_db);
    }

    [Fact]
    public async Task GetDecorationWithId_ShouldReturnDecoration_WhenExists()
    {
        // Arrange
        var userId = new Guid().ToString();

        var decorationId = new Guid().ToString();
        var decorations = new List<Decoration>()
        {
            new Decoration()
            {
                Id = decorationId,
                Name = "",
                OwnerId = userId,
            }
        };
        
        _db.Decorations.Returns(_decorationDbSet);
        _decorationDbSet.FirstOrDefaultAsync(t => t.Id == decorationId).Returns(decorations.FirstOrDefault());

        // Act
        var result = await _subject.GetDecorationWithId(userId, decorationId);

        // Assert
        Assert.Equal(result.Id, decorations[0].Id);
    }
}

但是,我收到以下错误:

“源 'IQueryable' 的提供程序未实现 'IAsyncQueryProvider'。只有实现 'IAsyncQueryProvider' 的提供程序才能用于实体框架异步操作。”

我在网上搜索过,但找不到好的参考资料。我该如何解决这个问题?

【问题讨论】:

标签: c# xunit nsubstitute


【解决方案1】:

如果你试图嘲笑DbSet,我认为你会经历很多痛苦和折磨。这直接来自 EFCore 的文档:https://docs.microsoft.com/en-us/ef/core/testing/#unit-testing

相反,您应该尝试使用真正的数据库或内存数据库。
在此处查看测试样本:https://docs.microsoft.com/en-us/ef/core/testing/testing-sample

【讨论】:

  • 谢谢。我将尝试关注该 Microsoft 文档页面。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-30
  • 2021-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-01
  • 1970-01-01
相关资源
最近更新 更多