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
0 votes
Hi,

I am using TypeMock Isolater 4.2.3.0 under .net 2.

I am mocking a SqlDataReader. I want to mock the Read() method so that it returns true the first time and false the second time. I have tried using the following code

MockObject mockReader = MockManager.MockObject(typeof(SqlDataReader),Constructor.NotMocked); mockReader.ExpectGetAlways("HasRows", true);
mockReader.ExpectAndReturn("Read", true,1);
mockReader.ExpectAndReturn("Read", false,1);


and I get the following error when executing my code:

TypeMock Verification: Method System.Data.SqlClient.SqlDataReader.Read() has 1 more expected calls

Any help would be appreciated.
asked by rensbuja (640 points)

2 Answers

0 votes
Your code is fine - you're just missing the actual usage of the expectation.
The following code should work:
MockObject mockReader = MockManager.MockObject(
                typeof(SqlDataReader), 
                Constructor.NotMocked); 
            
mockReader.ExpectGetAlways("HasRows", true);
mockReader.ExpectAndReturn("Read", true, 1);
mockReader.ExpectAndReturn("Read", false, 1);

SqlDataReader FakeSqlDataReader = mockReader.Object as sqlDataReader;

Assert.IsTrue(FakeSqlDataReader.HasRows);
Assert.IsTrue(FakeSqlDataReader.Read());
Assert.IsFalse(FakeSqlDataReader.Read());

MockManager.Verify();

As you can see after setting the expectation I can take a fake object by using mockReader.Object and run the code using it

Note:
To define behavior for future objects (objects that don't exist yet) use MockManager.Mock - this way the next time you create a new object of that type using new it will have the desired behavior.
answered by dhelper (11.9k points)
0 votes
okay - thanks for the prompt reply
answered by rensbuja (640 points)
...