How to mock an SqlDataReader using Moq - Update

后端 未结 5 1415
温柔的废话
温柔的废话 2021-01-30 17:12

I\'m new to moq and setting up mocks so i could do with a little help. How do I mock up an SqlDataReader using Moq?

Update

After further testing this is what I h

5条回答
  •  [愿得一人]
    2021-01-30 17:39

    After some testing the problem is trying to set the DataReader.Read() to true for one loop and then setting it to false. Rhino Mock has the Repeat.Once() option but I could not find a similar method in Moq (I might be wrong here).

    The main reason for testing this was the extension methods to convert the reader to the relevant datatype so in the end I removed the while loop and just accessed the values that had been setup in my mock. The code looks as follows:

    private IDataReader MockIDataReader()
    {
        var moq = new Mock();
        moq.SetupGet( 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() )
        {
           testData = new TestData
           {
               ValidChar = reader.GetChar( "Char" ).Value
           };
       }
    
       return testData;
    }
    
    
    

    Not an ideal solution but it works. If anyone knows better leave a comment thanks.

    提交回复
    热议问题