gmock
GMock testing destructor calls
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.
Delete foo object at the end of test so that it will not give object leak.
Related Links
gmock ReturnRef returns compilation error
How to call function pointer which is passed to Mock method?
In gmock, Is there a way to have mock object return an instance of an user defined object?
GMock testing destructor calls
set EXPECT_CALL to redirect the call to the original method
Capture GMOCK string parameter
Mocking non-virtual method generating errors
gmock matcher doesn't match my arguments by reference
What did you do to solve gmock you mentioned (link enclosed)?
how to set custom ref-variable in gmock