I have a method which needs a SqlDataReader object as parameter, and i have tests where i've mocked that object, and everything worked fine.
But, now i need to change that method. It should now only call new method, which has a IDataReader as parameter, and thats a problem, because, when I'm transfering the mocked SqlDataReader as a parameter of new method, it's losing his data, and i don't know why.
Something like this:
void method(SqlDataReader mockedObject)
{
// example property
mockedObject.FieldCount; // for example the value is 1;
newMethod(mockedObject);
}
void newMethod(IDataReader newObject)
{
// example property
newObject.FieldCount // here value is 0;
}
I observed that if i'm only copying the SqlDataReader object to the new variable of type IDataReader, data also are cleared.
Something like this:
void method(SqlDataReader mockedObject)
{
IDataReader variable = mockedObject;
}
the proper code:
=========================================================================================
[TestMethod()]
[DeploymentItem("IICMS.dll")]
public void CheckNullableDateTimeTest_SqlDataReader_Valid()
{
MockRepository mocks = new MockRepository();
SqlDataReader reader = mocks.DynamicMock<SqlDataReader>();
string column = "test";
DateTime? expected = new DateTime(2, 1, 1);
Nullable<DateTime> actual;
reader.Stub(r => r[column]).Return(expected);
reader.Stub(r => r.FieldCount).Return(1);
mocks.ReplayAll();
actual = Utility_Accessor.CheckNullableDateTime(reader, column);
Assert.AreEqual(expected, actual);
}
======================================================================================
public static DateTime? CheckNullableDateTime(SqlDataReader read, string column)
{
return GetValue<DateTime?>(read, column, null);
}
======================================================================================
public static T GetValue<T>(IDataReader reader, string columnName, T defaultValue)
{
try
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (reader.GetName(i) == columnName)
{
object value = reader[i];
return Convert.IsDBNull(value) ? defaultValue : (T)value;
}
}
return defaultValue;
}
catch
{
return defaultValue;
}
}
So there's the code, the second and the third method are in other dll but it doesn't have impact on anything. Object are mocked in RhinoMocks ;)
Data are losing after transfering SqlDataReader object (read) to GetValue method (i.e. FieldCount equals 0, in Check.. method it has proper value = 1)
I can't explain this but changing test method to the form below, makes, that all object fields are aviable in each method (CheckNullString and GetValue):