繁体   English   中英

模拟 IEnumerable<T> 使用最小起订量

[英]Mock IEnumerable<T> using moq

有了这个接口,我如何使用 moq 模拟这个对象?

public interface IMyCollection : IEnumerable<IMyObject>
{
    int Count { get; }
    IMyObject this[int index] { get; }
}

我得到:

无法将表达式类型 IEnumerable 转换为 IMyCollection

var itemMock = new Mock<IMyObject>();
List<IMyObject> items = new List<IMyObject> { itemMock.Object }; //<--IEnumerable<IMyObject>

var mock = new Mock<IMyCollection>();
mock.Setup(m => m.Count).Returns(() => items.Count);
mock.Setup(m => m[It.IsAny<int>()]).Returns<int>(i => items.ElementAt(i));
mock.Setup(m => m.GetEnumerator()).Returns(() => items.GetEnumerator());

模拟将使用具体的List来包装和公开测试所需的行为。

在 Count 的情况下,您需要使用SetupGet() 在索引器的情况下,使用

mock.Setup(m => m[It.IsAny<int>()])

返回所需的值

对于我的用例,我需要返回一个空的 IEnumerable。

mockObj.Setup(x => x.EnumerateBlah()).Returns(Enumerable.Empty<MyType>);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM