c# - 验证最小起订量中的可枚举列表

标签 c# unit-testing moq

我正在尝试为如下所示的方法编写单元测试:

public int Save(IEnumerable<int> addedIds, IEnumerable<int> removedIds)
{
    var existingIds = repository.Get();
    IEnumerable<int> ids = existingIds.Except(removedIds).Union(addedIds));
    return repository.Create(ids);
}

Moq 中的测试如下所示:

repository.Setup(r => r.Get()).Returns(CreateList());
service.Save(addedIds, removedIds);
repository.Verify(r => r.Create(It.Is<IEnumerable<int>>(l => VerifyList(l))));

这失败了,有这个错误,和VerifyList()永远不会被调用:

Expected invocation on the mock at least once, but was never performed:

r => r.Create(It.Is<IEnumerable'1>(list => VerifyList(list)))

Performed invocations:

IRepo.Create(System.Linq.Enumerable+<UnionIterator>d__88'1[System.Int32])

因为调用的类型不是 IEnumerable<int>但实际上是System.Linq.Enumerable+<UnionIterator>d__88'1[System.Int32]) ,测试失败。 (逐步测试,一切正常,结果符合预期)

如果我调用 ids.ToList()在被测方法中,结果如下:

Expected invocation on the mock at least once, but was never performed:

r => r.Create(It.Is<List'1>(l => VerifyList(l)))

Performed invocations: IRepo.Create(System.Collections.Generic.List'1[System.Int32])

有什么办法解决这个问题吗?还是我做错了什么?

编辑:原来我的 VerifyList 方法有一个错误,所以它返回 false,但 Moq 没有给我那个信息。类型差异是一条红鲱鱼..

最佳答案

这似乎有效。虽然做了一些假设。猜测 VerifyList 方法可能会更好。 =)

[Test]
    public void Test()
    {
        // SETUP
        Mock<IRepository> repository = new Mock<IRepository>();
        Service service = new Service(repository.Object);
        repository.Setup(r => r.Get()).Returns(CreateList());

        IEnumerable<int> addedIds = new[]{1,2};
        IEnumerable<int> removedIds = new[]{3,4};
        service.Save(addedIds, removedIds);

        repository.Verify(r => r.Create(It.Is<IEnumerable<int>>(l => VerifyList(l))));
    }

    private static bool VerifyList(IEnumerable<int> enumerable)
    {
        return enumerable.Contains(1) && enumerable.Contains(2) && enumerable.Contains(5);
    }

    private IEnumerable<int> CreateList()
    {
        return new[] { 3, 4, 5 };
    }

    public interface IRepository
    {
        IEnumerable<int> Get();
        int Create(IEnumerable<int> id);
    }
    public class Service
    {
        public Service(IRepository repository)
        {
            this.repository = repository;
        }

        private IRepository repository;

        public int Save(IEnumerable<int> addedIds, IEnumerable<int> removedIds)
    {
        var existingIds = repository.Get();
            IEnumerable<int> ids = existingIds.Except(removedIds).Union(addedIds);

        return repository.Create(ids);
    }

关于c# - 验证最小起订量中的可枚举列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14501254/

相关文章:

c# - WebHierarchicalDatagrid 在初始页面加载时不显示任何数据

java - Mockito 验证构造函数调用方法

java - 如何使用 easymock Capture 进行测试

unit-testing - 如何使用 Moq 模拟 Microsoft.Extensions.Logging

c# - 选择新的关键字组合

c# - 如何让linq将数据从一种形式转换为另一种形式

android - 如何将 TestNG 集成到 Android 项目中?

c# - 每次使用 Moq 调用方法时,如何使 Mock 返回一个新列表

c# - 测试在最小起订量中多次调用的方法

c# - C# 面板和 UserControl 之间的区别