R – Is it possible to generate partial stubs with Rhino Mocks

rhino-mocksstub

I am new to unittesting and mocking in general and am trying to set up tests for one of my classes where I want to make sure that a particular method is called from another method within the same class. I would therefore like to use the concrete implementation but mock out parts of it. Is this possible?

public class MyClass
{
  public Accounts[] GetAccounts()
  {
      return GetAccounts(null);
  }

  public Accounts[] GetAccounts(CustomerId id)
  {
      if(id == null)
      {
          // Get all accounts
      }
  }
}

I therefore am trying to set up a stub that will get GetAccounts() called (which I want to use the concrete implementation) but I would like to check if that method calls GetAccounts(null).

[Test]
public void GetAccountsTest()
{
  MockRepository mocks = new MockRepository();
  MyClass stub = mocks.Stub();
  using(mocks.Record())
  {
     Expect.Call(() => stub.GetAccounts()).CallOriginalMethod();
     Expect.Call(() => stub.GetAccounts(null));
  }
  mocks.ReplayAll();
  stub.GetAccounts();
  mocks.VerifyAll();
}

Problem is that the concrete class gets called on the CallOriginalMethod() line which I am expecting to get called during the replay when I call stub.GetAccounts().
So both during the recording as well as when I am performing the tests the concrete methods of the implementation are called when I simply want to mock them out – well partially as I have explained. Is this a misunderstanding on my part? Should I not be able to mock/stub concrete classes as well as interfaces?

Do I need to add virtual keyword to the methods I want to be able to mock out?

Is this even possible? How would I do it?

Best Answer

Looks like you might want to use a PartialMock. It will allow you to mock virtual methods.