views:

613

answers:

1

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?

+2  A: 

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

Cristian Libardo
That would probably suit me but the problem is that when setting up the stub/mock the methods are called for some reason where I only want to setup the expectencies.
Fadeproof
Is that the exact code you are testing with? Try making the methods virtual.
Cristian Libardo
Making them virtual seems to do the trick. Is that the trick? Making all methods I want to use in stubs/mocks virtual?
Fadeproof
Behind the scenes rhino will create a new class during runtime that inherit from your class. Unless you make the methods virtual it's not possible to intercept the call to the method (due to the way .NET is designed).
Cristian Libardo