views:

68

answers:

3

Is it true that mocking frameworks in general and Rhino mocking in specific only mocks interfaces and classes that have virtual method? For example can I mock following simple class:

public class MyClass
{
    void method1()
    {
        //some code goes here
    }
}

If the answer is true, why such a limitation exists? Is there any work-around?

+5  A: 

The limitation exists, because the mocking frameworks cannot change method1 without it being virtual or an interface. It is a reasonable limitation, since interfaces allow you to decouple your dependencies and is a common trait of good code, IMO. Unfortunately, most of the .Net framework does not have virtual methods or interfaces... which requires ugly wrapping in order to create interfaces.

If you really don't like it, one mocking framework option out there that gets past the limitation by hooking the CLR with some crazy magic foo. That famework is called TypeMock Isolator.

Brian Genisio
You can detour non-interface or even static calls in a similar way using MS Moles, though Moles is still experimental and not a full mocking framework: http://research.microsoft.com/en-us/projects/moles/
Dan Bryant
Brian - I wouldn't really call it "crazy magic foo". It's just the Microsoft Profiling API (http://msdn.microsoft.com/en-us/library/bb384382%28VS.90%29.aspx). :)
Patrick Steele
@Patrick Steele: Fair enough. It just FEELS like crazy magic foo :)
Brian Genisio
+1  A: 

I am not sure how you would mock a class that did not implement an interface or have virtual methods. If some code is expecting an instance of MyClass and you pass it an instance of MyDerivedMockClass, then the MyClass members will be accessed not MyDerivedMockClass members because they are not overridden virtual members.

Ben Robinson
A: 

Typemock is your best bet.

http://site.typemock.com/

Dmitry