Moq 在添加新数据后不验证对 DbSet 和 DbContext 的操作

Moq doesn't verify actions on DbSet and DbContext after adding new data

我有以下使用 Moq 的 xunit 测试

[Fact]
public async void Add_Valid()
{
    // Arrange
    var mockSet = new Mock<DbSet<CategoryDao>>();

    var mockContext = new Mock<Data.Context.AppContext>();
    mockContext.Setup(m => m.Categories).Returns(mockSet.Object);

    var categoryProfile = new CategoryVoProfile();
    var configMapper = new MapperConfiguration(cfg => cfg.AddProfile(categoryProfile));
    IMapper mapper = new Mapper(configMapper);

    var service = new InDbCategoryService(mockContext.Object, mapper);

    // Act
    await service.Add(new CategoryVo() { Name = "CreatedName1" });

    // Assert
    mockSet.Verify(m => m.Add(It.IsAny<CategoryDao>()), Times.Once()); // DbSet verification
    mockContext.Verify(m => m.SaveChanges(), Times.Once());            // DbContext verification
}

它抛出这个错误:

Moq.MockException:
Expected invocation on the mock once, but was 0 times: m => m.Add(It.IsAny())

Performed invocations:
Mock<DbSet:1> (m): No invocations performed.

当我删除 DbSet 验证行并要求仅验证 DbContext 时,它会抛出此消息:

Moq.MockException :
Expected invocation on the mock once, but was 0 times: m => m.SaveChanges()

Performed invocations:
MockAppContext:1 (m):
AppContext.Categories = InternalDbSet
DbContext.Add(CategoryDao)
DbContext.SaveChangesAsync(CancellationToken)


简化的服务如下所示:

public class InDbCategoryService : IDataServiceAsync<CategoryVo>
{
    private readonly Data.Context.AppContext context;
    private readonly IMapper mapper;
    public InDbCategoryService(Data.Context.AppContext context, IMapper mapper)
    {
        this.context = context;
        this.mapper = mapper;
    }

    public async Task Add(CategoryVo item)
    {
        context.Add(entity: mapper.Map<CategoryDao>(item));
        await context.SaveChangesAsync();
    }
}

类别简介:

public class CategoryVoProfile : Profile
{
    public CategoryVoProfile()
    {
        CreateMap<CategoryDao, CategoryVo>()
            .ReverseMap();
    }
}

数据库上下文:

public class AppContext : DbContext
{
    public AppContext() { }

    public AppContext (DbContextOptions<AppContext> options) : base(options) { }

    public virtual DbSet<CategoryDao> Categories { get; set; }

}

我已经使用 this microsoft docs example 进行测试,但很明显我遗漏了一些东西。感谢任何帮助或建议。

您没有测试您在服务中调用的方法。您的添加方式:

public async Task Add(CategoryVo item)
{
    context.Add(entity: mapper.Map<CategoryDao>(item));
    await context.SaveChangesAsync();
}

你会注意到你调用的是 DbContext.Add 而不是你在测试中验证的 context.Categories.Add:

mockSet.Verify(m => m.Add(It.IsAny<CategoryDao>()), Times.Once());

您的 SaveChanges 也是如此。您正在验证同步版本但调用异步版本。因此,您需要修改您正在验证的内容以匹配您正在使用的内容。