I\'m new to moq and setting up mocks so i could do with a little help. How do I mock up an SqlDataReader using Moq?
Update
After further testing this is what I h
Inspired by @mikesigs answer and another question: SetupSequence in Moq I've came up with the following extension method that does the work for you:
public static void SetupDataReader(this Mock dataReaderMock, IList columnNames, ICollection collection)
{
var queue = new Queue(collection);
dataReaderMock
.Setup(x => x.Read())
.Returns(() => queue.Count > 0)
.Callback(() =>
{
if (queue.Count > 0)
{
var row = queue.Dequeue();
foreach (var columnName in columnNames)
{
var columnValue = row.GetType().GetProperty(columnName).GetValue(row);
dataReaderMock
.Setup(x => x[columnNames.IndexOf(columnName)])
.Returns(columnValue);
dataReaderMock
.Setup(x => x[columnName])
.Returns(columnValue);
}
}
});
}
And the usage example:
var foundTargetIds = new[] { 1, 2, 3 };
var dataReaderMock = new Mock();
dataReaderMock.SetupDataReader(new[] { "TargetId" }, foundTargetIds.Select(x => new { TargetId = x }).ToList());