chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
how do you mock the idatareader in vb.net.

here is the idatareader property:
ReadOnly Default Property Item(ByVal name As String) As Object
ReadOnly Default Property Item(ByVal i As Integer) As Object

here is my mock code:
mockReader.ExpectGetIndex("LastName").Args("LastName")

here is the real code:
m_customer.LastName = DirectCast(dataReader("LastName"), String)

the error is:
System.MissingMemberException {"No default member found for type 'MockIDataReader'."}

thanks in advance.
asked by mzelinski (2.2k points)

1 Answer

0 votes
Hi,

I'll put my answer at the end, and you can look at the C# version in the movie on mocking database calls here: https://www.typemock.com/Multimedia.html#identifier3

However, apart from technically doing so, which is obviously possible, I would think first about what you are trying to accomplish.

If you resort to mocking database objects and interfaces, you should probably refactor your code. Encapsulate your data access code in a single method, then mock that method and return what you want. Like I said, it is technically possible, but will make your unit tests very dependent on the database scheme, and thus brittle.

If you want, you can post your code here, (your database access code), and we can comment on it. Or you can just email me a solution, and we'll take it offline.

Look at this test code in VB.Net:
    <TestMethod()> Public Sub TestMethod1()

        Using rec As RecordExpectations = RecorderManager.StartRecording
            Using connection As New SqlConnection
                Dim command As New SqlCommand(Nothing, Nothing)
                connection.Open()

                Dim fakeReader As SqlDataReader = RecorderManager.CreateMockedObject(GetType(SqlDataReader))
                rec.ExpectAndReturn(command.ExecuteReader, fakeReader)
                rec.ExpectAndReturn(fakeReader.Read(), False)
                rec.ExpectAndReturn(fakeReader.HasRows, True)
                rec.ExpectAndReturn(fakeReader.Item("LastName"), "Gil")
                fakeReader.Close()
            End Using
        End Using

    End Sub


As you can see there's a lot of code to write just to return "Gil" for the indexer LastName. (And it's not shorter using Reflective mocks). These are things that you need to mock just to get to the data reader.
Instead, if you method GetLastName does all the data access, you can easily mock it and return your value in a single line.

Let me know if this helps you.
answered by gilz (14.5k points)
...