Convert IDataReader to SQLDataReader

3.9k views Asked by At

Is there a way to convert IDataReader object to SqlDataReader object? I am trying to break database dependency to one of API, by intercepting SqlHelper by with my own IDataReader (since I can't create a SqlDataReader object).

This is how my test case looks like (and evaluating TypeMock):

Isolate.Fake.StaticMethods(typeof(SqlHelper));
Isolate.WhenCalled(() => SqlHelper.ExecuteReader(string.Empty, CommandType.StoredProcedure, string.Empty))
     .WillReturn(myDataGenerator.ToDataReader() as SqlDataReader);

This get compiled with no problem, but does not return any rows. When I debug I see that it does not have any rows at all. Any thoughts?

Thanks in advance.

Edit(1): Since conversion is not possible, is it possible to mock SqlDataReader.

2

There are 2 answers

3
shf301 On

No you can't convert a IDataReader to a SqlDataReader. SqlDataReader is a IDataReader - an SqlDataReader can be converted to an IDataReader not the otherway around.

Your real problem is that your code wasn't written to be testable. Really SqlHelper should be an instance class is passed in and can be mocked and returns an IDataReader. Or the method or methods that you are testing can be refactored so they don't rely on SqlHelper direclty and take IDataReader's.

However if as I suspect you don't control this code, you can create your own DataReader that inherits from SqlDataReader. All the IDataReader methods are virtual so you can override them your self.

0
Jamie On

So your SqlHelper.ExecuteReader supposed to return a SqlDataReader? Why don't you just have your SqlHelper.ExecuteReader use an IDataReader.

The answer by shf301 was just posted and is better written than mine, but exactly what you need to know.