The other day I was writing unit tests for some legacy code and I needed to mock IDataReader. I really just wanted to populate the reader with a single row of data, then the Read() method should return false. Using Rhino.Mocks it was a piece of cake.
IDataReader reader = MockRepository.GenerateStub<IDataReader>(); reader.Stub(x => x.Read()).Return(true).Repeat.Times(1); reader.Stub(x => x.Read()).Return(false); reader.Stub(x => x["ID"]).Return(Guid.Empty); reader.Stub(x => x["FullName"]).Return("Test User"); List<UserDTO> list = SearchProvider.ParseUserData(reader); Assert.IsNotNull(list);
The magic happens in the Repeat.Times(1) statement. This tells Rhino.Mocks that when the method is called, the mock should Return the given value that number of times. After that it can return a different value.
Update: Jeremy Miller told me about the DataTableReader class in the BCL and that you can use it to stub out IDataReader. I like this better because it removes the dependency the test had on Rhino.Mocks.
DataTable table = new DataTable(); DataRow row = table.NewRow(); table.Columns.Add(new DataColumn("ID")); table.Columns.Add(new DataColumn("FullName")); row["DirectoryUserID"] = Guid.Empty; row["FullName"] = "Test User"; table.Rows.Add(row); DataTableReader reader = new DataTableReader(table);