Search code examples
c#unit-testingrhino-mocks

Rhino Mock Expect() method triggers call on expected function


I am using Rhino Mocks 3.6 in C# and i am experiencing problems when mocking objects instead of interfaces. Could somebody please explain why methods are actually called when just defining an expectation?

   public class MockingBird
   {
      public void TestMethod()
      {
         throw new Exception("Method call!");
      }
   }

...

 [TestMethod]
  public void TestMock()
  {
     var mockedMockingBird = MockRepository.GenerateStrictMock<MockingBird>();
     mockedMockingBird.Expect(x => x.TestMethod());
  }

Solution

  • You can't mock methods that are not overridable. When creating mock instance Rhino does the following:

    1. It generates dynamic assembly in runtime (using Castle Dynamic Proxy library to do that)
    2. In that assembly Rhino creates a new type, deriving from the type you want to mock
    3. Members of that new type are overridden to insert recording/stubbing logic

    In practice, you can only mock virtual/abstract methods of classes and any member of interface.

    Keep in mind that this limitation is present in all free mocking frameworks.