Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 343
ShaneKm Avatar asked Dec 08 '16 21:12

ShaneKm


2 Answers

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.

like image 52
Nkosi Avatar answered Sep 18 '22 02:09

Nkosi


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

like image 24
jparaya Avatar answered Sep 17 '22 02:09

jparaya