加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 验证Moq中的可枚举列表

发布时间:2020-12-15 04:15:02 所属栏目:百科 来源:网络整理
导读:我正在尝试为一个看起来像这样的方法编写一个单元测试: public int Save(IEnumerableint addedIds,IEnumerableint removedIds){ var existingIds = repository.Get(); IEnumerableint ids = existingIds.Except(removedIds).Union(addedIds)); return repos
我正在尝试为一个看起来像这样的方法编写一个单元测试:
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没有给我这些信息.类型差异是红鲱鱼..

解决方法

这似乎有效.但是做了一些假设.猜猜验证方法可能更好. =)
[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);
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读