I've read the section in the gmock cookbook on Mocking Destructors but I'm having no luck getting it to work. My code is almost exactly what the doc says:
class MockFoo : public Foo {
public:
MockFoo() {}
MOCK_METHOD0(destroyMockFoo, void());
virtual ~MockFoo() { destroyMockFoo(); }
};
TEST_F(DestructorTest, shouldFail) {
MockFoo* foo = new MockFoo();
EXPECT_CALL(*foo, destroyMockFoo());
}
But when I run the code, the test passes with no errors. I do get the error at the end of the test output about the leaked object:
DestructorTest.cpp:149: ERROR: this mock object (used in test DestructorTest.shouldFail) should be deleted but never is. Its address is @0x8178790.
ERROR: 1 leaked mock object found at program exit.
but this is not what I want nor is it what the doc says should happen.
So what am doing wrong?
You're not doing anything wrong, necessarily. The problem here is that gmock expectations are verified in the destructor of the mock object, so if the destructor is never called, then the expectations are never verified. This is what's happening in your example.
The easy way to get around this is to explicitly verify the expectations on the mock:
Mock::VerifyAndClearExpectations(foo);
This will give you the behavior that you're looking for.