I'm new to Moq and I'm struggling to write Unit Test to test a method which converts SqlDataAdapter
to System.DataView
. This is my method:
private DataView ResolveDataReader(IDataReader dataReader)
{
DataTable table = new DataTable();
for (int count = 0; count < dataReader.FieldCount; count++)
{
DataColumn col = new DataColumn(dataReader.GetName(count),
dataReader.GetFieldType(count));
table.Columns.Add(col);
}
while (dataReader.Read())
{
DataRow dr = table.NewRow();
for (int i = 0; i < dataReader.FieldCount; i++)
{
dr[i] = dataReader.GetValue(dataReader.GetOrdinal(dataReader.GetName(i)));
}
table.Rows.Add(dr);
}
return table.DefaultView;
}
I'm trying to create to create something like:
var dataReaderMock = new Mock<IDataReader>();
var records = new Mock<IDataRecord>();
dataReaderMock.Setup(x => x.FieldCount).Returns(2);
dataReaderMock.Setup(x => x.Read()).Returns(() => records);
I would like to pass some data and verify that it is converted.
Thanks.
You were on the right track with your mocks, but
dataReaderMock.Setup(x => x.Read()).Returns(() => records);
is where you went wrong as.Read
returns a bool, not the records themselves, which are read out theIDataReader
by your method.To arrange the mocks:
You can arrange the columns to taste to simulate more real data, types etc.. in your system, just ensure the first count, the number of
GetName
s and the number ofGetFieldType
s are in sync.To arrange the
.Read()
, we can use SetupSequence:To use this in tests you can extract it into a method:
(Alternatively, you could arrange this on a
Setup
, if that makes more sense for your test class - in that case thedataReader
mock would be a field, not a returned value)Example Tests. Then it can be used like:
(I've used NUnit, but it'll be similar with just a different attribute on the test method and a different assert syntax, for different test frameworks)
As an aside, I got the above to work by changing
ResolveDataReader
tointernal
and settingInternalsVisibleTo
, but I assume you have a gateway into this private method as you've got as far as you did with trying to test it.My class to setup
IDataReader
mock:Usage: