使用最小起订量模拟 IEnumerable<T>
Mock IEnumerable<T> using moq
有了这个接口,如何使用最小起订量模拟这个对象?
public interface IMyCollection : IEnumerable<IMyObject>
{
int Count { get; }
IMyObject this[int index] { get; }
}
我得到:
can not convert expression type IEnumerable to IMyCollection
Count的话,需要用到SetupGet()。在索引器的情况下,使用
mock.Setup(m => m[It.IsAny<int>()])
到return想要的值
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
包装和公开测试所需的行为。
对于我的用例,我需要 return 一个空的 IEnumerable。
mockObj.Setup(x => x.EnumerateBlah()).Returns(Enumerable.Empty<MyType>);
有了这个接口,如何使用最小起订量模拟这个对象?
public interface IMyCollection : IEnumerable<IMyObject>
{
int Count { get; }
IMyObject this[int index] { get; }
}
我得到:
can not convert expression type IEnumerable to IMyCollection
Count的话,需要用到SetupGet()。在索引器的情况下,使用
mock.Setup(m => m[It.IsAny<int>()])
到return想要的值
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
包装和公开测试所需的行为。
对于我的用例,我需要 return 一个空的 IEnumerable。
mockObj.Setup(x => x.EnumerateBlah()).Returns(Enumerable.Empty<MyType>);