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.
CODE:
-
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.
CODE:
-
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);

2 Comments
Much better then using the ugly Do(Func) thingy. And if you compare the new AAA syntax to the old RM syntax, its so much shorter. I wouldn’t have tried to do stuff like this with the old RM.
goog inform
2 Trackbacks/Pingbacks
[...] Shared Mocking IDataReader using Rhino.Mocks 3.5 | Lazycoder [...]
[...] http://www.lazycoder.com/weblog/2008/12/12/mocking-idatareader-using-rhinomocks-35/ [...]
Post a Comment