Hibernating Rhinos | Mocking a Read-Only Property

If you come into a situation where you need to mock a read-only property on a class, here is how to do so:

   1: /// <summary>
   2: /// When you need to mock a read-only property of a class.
   3: /// </summary>
   4: [Test]
   5: public void How_to_Stub_out_your_own_value_of_a_ReadOnlyProperty()
   6: {
   7:     // Arrange
   8:     var foo = MockRepository.GenerateStub<IFoo>();
   9:     foo.Stub(x => x.ID).Return(123);
  10:  
  11:     // Act
  12:     var id = foo.ID;
  13:  
  14:     // Assert
  15:     Assert.That(id, Is.EqualTo(123));
  16: }

This code is fairly simple and straightforward. Using MockRepository.GenerateStub<T>, you'll mock an instance of IFoo, then have the ability to control what the return value is for a specific function. After the line declaring and setting the variable "foo", you'll see that I'm using the Stub extension method to pass a lambda expression of the property of which I want to control the return value. Now, my instance of IFoo will return 123 whenever the property ID is retrieved.

This test isn't testing any business logic, it just shows how to control the return value of a read-only property. For the entire code example, please check out the RhinoMocks.GettingStarted project.

This example can be found in code here: http://github.com/ayende/rhino-mocks/blob/master/Rhino.Mocks.GettingStarted/Stubs.cs#L24

Last update: 12/8/2009 5:08:28 AM