Nerdy tidbits from my life as a software engineer

Thursday, December 11, 2008

Introducing ‘Mimics’

With the coming release of .NET 4.0, I think we’re going to see the creation of a new type of unit testing object which I’ve decided to call a mimic.  A mock object requires polymorphism in order to work:


This requirement is due to the fact that without the help of virtual methods, there is no way to dynamically call another object that behaves like the Target unless it inherits from Target.  In most cases this isn’t a problem, but if Foo and Bar are not declared virtual, then you’re out of luck because the method pointer is determined at compile time instead of run time.  In those cases, there is no way to generate a Mock object and use it without altering some existing code.  Mock frameworks can’t work with these scenarios (unless they hijack the clr use the profiler API to dynamically insert different object types at runtime…see TypeMock).

But with the coming dynamics feature in .NET 4.0, you’ll be able to call Foo and Bar on instances of both Target and Mock, even if Mock is not a Target but behaves exactly the same way.  In other words, Mock is like a Target, but is not actually a target - it mimics the target.  The relationship looks like this:


I have a framework that I’ve been working on for the last couple months that has an implementation of a Mimic.  It’s not a difficult thing to do, I’m just really itching to see it work in action.  The breakthrough should make it a lot easier to unit test certain API’s (such as the WPF) that are currently very difficult to test because the vast majority of their methods are not virtual.