ShaneKm
ShaneKm

Reputation: 21328

Mock IEnumerable<T> using moq

Having this interface, how can I mock this object using moq?

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

I get:

can not convert expression type IEnumerable to IMyCollection

Upvotes: 28

Views: 27651

Answers (3)

For my use cases I need to return an empty IEnumerable.

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

Upvotes: -1

Nkosi
Nkosi

Reputation: 247058

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.

Upvotes: 53

jparaya
jparaya

Reputation: 1339

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

Upvotes: 3

Related Questions