Reputation: 1705
I am thinking to mock an extension method (used in project) over IDataReader
. I want to return a test data collection when ReadAll()
(below) is called.
public static IEnumerable<object[]> ReadAll(this IDataReader reader)
{
while (reader.Read())
{
var values = new object[reader.FieldCount];
reader.GetValues(values);
yield return values;
}
}
I am aiming to return a custom IEnumerable<object[]>
collection. I mocked Read()
method by checking the count against the custom collection,
int count = -1;
var testData = ReadData(); //Custom collection
DataReaderInfoMock.Setup(x => x.DataReader.Read()).Returns(() => count < testData.Count() - 1).Callback(() => count++);
However, I cannot think of way to mock implementation under Read()
block, if at all that is possible.
Is there any way I could test it?
Upvotes: 2
Views: 956
Reputation: 275
You can't mock an extension method, but you could write your own implementation of IDataReader to use as a mock.
Like so (I only wrote the methods you need, IDataReader has many more):
class MockDataReader : IDataReader
{
private List<object[]> _data;
private int _current = -1;
public MockDataReader(List<object[]> data)
{
_data = data;
}
public int FieldCount
{
get
{
return _data.FirstOrDefault()?.Length ?? 0;
}
}
public int GetValues(object[] values)
{
object[] record = _data[_current];
for (int i = 0; i < record.Length; i++)
{
values[i] = record[i];
}
return record.Length;
}
public bool Read()
{
_current++;
return _current < _data.Count;
}
}
Upvotes: 2