Mock IEnumerable<T> using moq

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.


In the case of Count, you need to use SetupGet(). In the case of the Indexer, use

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

to return the desired value