Mocking using boost::shared_ptr and AMOP
- by Edison Gustavo Muenz
Hi, I'm trying to write mocks using amop. I'm using Visual Studio 2008.
I have this interface class:
struct Interface {
virtual void Activate() = 0;
};
and this other class which receives pointers to this Interface, like this:
struct UserOfInterface {
void execute(Interface* iface) {
iface->Activate();
}
};
So I try to write some testing code like this:
amop::TMockObject<Interface> mock;
mock.Method(&Interface::Activate).Count(1);
UserOfInterface user;
user.execute((Interface*)mock);
mock.Verifiy();
It works! So far so good, but what I really want is a boost::shared_ptr in the execute() method, so I write this:
struct UserOfInterface {
void execute(boost::shared_ptr<Interface> iface) {
iface->Activate();
}
};
How should the test code be now? I tried some things, like:
amop::TMockObject<Interface> mock;
mock.Method(&Interface::Activate).Count(1);
UserOfInterface user;
boost::shared_ptr<Interface> mockAsPtr((Interface*)mock);
user.execute(mockAsPtr);
mock.Verifiy();
It compiles, but obviously crashes, since at the end of the scope the variable 'mock' gets double destroyed (because of the stack variable 'mock' and the shared_ptr).
I also tried to create the 'mock' variable on the heap:
amop::TMockObject<Interface>* mock(new amop::TMockObject<Interface>);
mock->Method(&Interface::Activate).Count(1);
UserOfInterface user;
boost::shared_ptr<Interface> mockAsPtr((Interface*)*mock);
user.execute(mockAsPtr);
mock->Verifiy();
But it doesn't work, somehow it enters an infinite loop, before I had a problem with boost not finding the destructor for the mocked object when the shared_ptr tried to delete the object.
Has anyone used amop with boost::shared_ptr successfully?