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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With