Mock IEnumerable <T> using moq

With this interface, how can I mock this object using moq? A.

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

I get:

cannot convert IEnumerable expression type to IMyCollection

+4
source share
2 answers
var itemMock = new Mock<IMyObject>();
var 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 layout will use the specific Listto wrap and identify the desired behavior for the test.

+10
source

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

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

to return the desired value

+2
source

Source: https://habr.com/ru/post/1663277/


All Articles