m0cxx0r - Compiler Generated Mock Objects For C++

Sun 26 October 2008 by Jim Purbrick

A few weeks ago at JAOO I felt insanely jealous while watching Erik Doernenburg demo Mockito: I wanted dynamic mock objects in C++. It turns out that it’s really hard. However, after a few days hacking around I found that it’s not completely impossible. The results of my hacking are now available under a BSD license here. m0cxx0r lets you write tests like this in C++:

typedef m0cxx0r::Mock<ProductionClass> MockClass;
MockClass* mock = MockClass::create();
mock->expect("foo", &ProductionClass::foo);
mock->expect("bar", &ProductionClass::bar, 42);
mock->expect("baz", &ProductionClass::baz);
mock->foo();
mock->bar(3);                                                     
mock->verify();
MockClass::destroy(&mock);

Most importantly you don’t need to hand code a test double for ProductionClass: m0cxx0r generates it for you. The code needs lots of love: it’s all in a single file and the interface will need iterating a few times, but I think it’s a good start. Please download it, have a play and let me know what you come up with. I’ve only tested it on gcc version 4.0.1 on darwin, so I’d be interested to know if it works on other platforms as it uses some code layout assumptions that might not be portable. I’ll write some blog posts over the next few days that explain how it all works.


Comments