How to mock an SqlDataReader using Moq - Update

Posted by Simon G on Stack Overflow See other posts from Stack Overflow or by Simon G
Published on 2010-04-15T08:55:07Z Indexed on 2010/04/15 13:23 UTC
Read the original article Hit count: 2910

Filed under:
|
|

Hi,

I'm new to moq and setting up mocks so i could do with a little help.

Title says it all really - how do I mock up an SqlDataReader using Moq?

Thanks

Update

After further testing this is what I have so far:

private IDataReader MockIDataReader()
{
    var moq = new Mock<IDataReader>();
    moq.Setup( x => x.Read() ).Returns( true );
    moq.Setup( x => x.Read() ).Returns( false );
    moq.SetupGet<object>( x => x["Char"] ).Returns( 'C' );

    return moq.Object;
}

private class TestData
{
    public char ValidChar { get; set; }
}

private TestData GetTestData()
{
   var testData = new TestData();

   using ( var reader = MockIDataReader() )
   {
       while ( reader.Read() )
       {
           testData = new TestData
           {
               ValidChar = reader.GetChar( "Char" ).Value
           };
       }
   }

   return testData;
}

The issue you is when I do reader.Read in my GetTestData() method its always empty. I need to know how to do something like

reader.Stub( x => x.Read() ).Repeat.Once().Return( true ) 

as per the rhino mock example: http://stackoverflow.com/questions/1792984/mocking-a-datareader-and-getting-a-rhino-mocks-exceptions-expectationviolationexc

© Stack Overflow or respective owner

Related posts about unit-testing

Related posts about mocking