C# · 12月 25, 2021

c# – 验证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没有给我这些信息.类型差异是红鲱鱼..

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