Search code examples
c#rhino-mocksrhino-mocks-3.5

Rhino - Mocking classes and not overriding virtual methods


If I'm mocking a class, like below, is there any way I can get the mock to not override a virtual method? I know I can simply remove the virtual modifier, but I actually want to stub out behavior for this method later.

In other words, how can I get this test to pass, other than removing the virtual modifier:

namespace Sandbox {
    public class classToMock {
       public int IntProperty { get; set; }

       public virtual void DoIt() {
           IntProperty = 1;
       }
}

public class Foo {
    static void Main(string[] args) {
        classToMock c = MockRepository.GenerateMock<classToMock>();
        c.DoIt();

        Assert.AreEqual(1, c.IntProperty);
        Console.WriteLine("Pass");
    }
}

}


Solution

  • You want to use a partial mock, which will only override the method when you create an expectation:

    classToMock c = MockRepository.GeneratePartialMock<classToMock>();
    c.DoIt();
    
    Assert.AreEqual(1, c.IntProperty);