Skip to content

Mocking IDataReader using Rhino.Mocks 3.5

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:
  1. IDataReader reader = MockRepository.GenerateStub<IDataReader>();
  2.  
  3.             reader.Stub(x => x.Read()).Return(true).Repeat.Times(1);
  4.  
  5.             reader.Stub(x => x.Read()).Return(false);
  6.  
  7.             reader.Stub(x => x["ID"]).Return(Guid.Empty);
  8.  
  9.             reader.Stub(x => x["FullName"]).Return("Test User");
  10.  
  11.  
  12.  
  13.             List<UserDTO> list = SearchProvider.ParseUserData(reader);
  14.  
  15.             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:
  1. DataTable table = new DataTable();
  2.             DataRow row = table.NewRow();
  3.             table.Columns.Add(new DataColumn("ID"));
  4.             table.Columns.Add(new DataColumn("FullName"));
  5.             row["DirectoryUserID"] = Guid.Empty;
  6.             row["FullName"] = "Test User";
  7.             table.Rows.Add(row);
  8.             DataTableReader reader = new DataTableReader(table);

Share and Enjoy:
  • del.icio.us
  • DotNetKicks
  • DZone
  • Reddit
  • Digg
  • StumbleUpon
  • LinkedIn
  • Facebook
  • FriendFeed
  • HackerNews
  • Netvibes
  • Posterous
  • Tumblr
  • Twitter

2 Comments

  1. 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.

    Posted on 12-Dec-08 at 12:25 pm | Permalink
  2. goog inform

    Posted on 07-Mar-10 at 5:39 am | Permalink

2 Trackbacks/Pingbacks

  1. [...] Shared Mocking IDataReader using Rhino.Mocks 3.5 | Lazycoder [...]

  2. Mocks versus stubs and fakes | Lazycoder on 12-Oct-09 at 10:00 am

    [...]  http://www.lazycoder.com/weblog/2008/12/12/mocking-idatareader-using-rhinomocks-35/ [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*

Get Adobe Flash playerPlugin by wpburn.com wordpress themes