简体   繁体   English

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

[英]Mock IEnumerable<T> using moq

Having this interface, how can I mock this object using moq?有了这个接口,我如何使用 moq 模拟这个对象?

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

I get:我得到:

can not convert expression type IEnumerable to IMyCollection无法将表达式类型 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());

The mock will use the concrete List to wrap and expose the desired behavior for the test.模拟将使用具体的List来包装和公开测试所需的行为。

In the case of Count, you need to use SetupGet() .在 Count 的情况下,您需要使用SetupGet() In the case of the Indexer, use在索引器的情况下,使用

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

to return the desired value返回所需的值

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

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

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

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