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
对于我的用例,我需要返回一个空的 IEnumerable。
mockObj.Setup(x => x.EnumerateBlah()).Returns(Enumerable.Empty<MyType>);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.