2

When I store my mock object on the heap using a shared_ptr, the expectations are satisfied and the pointer is destroyed but GMock framework thinks the mock object is still alive:

// Using a mock object
MockFoo foo;
EXPECT_CALL(foo, doSomething());
foo.doSomething();
// Test passes without warnings
// Using shared_ptr to a mock object
auto foo_sp = std::make_shared<MockFoo>();
EXPECT_CALL(*foo_sp, doSomething());
A a(std::move(foo_sp));
a.useFoo();
// a is then deleted
...
// in useFoo:
foo_sp->doSomething();
...
// Test passes WITH warnings that mock object is still alive

Is this a bug in the Google mock framework? If not then how can I store my mock object on the heap in a smart pointer and use it correctly?

273K
  • 29,503
  • 10
  • 41
  • 64
pooya13
  • 2,060
  • 2
  • 23
  • 29
  • 2
    What are `foo` and `mock` in your second example? – YSC Jun 27 '19 at 06:43
  • 2
    I think problem is somewhere deeper. Simple empty class MockFoo doesn't give any warnings for me... – sklott Jun 27 '19 at 06:48
  • 2
    Is it related to this: [Why is GoogleMock leaking my shared_ptr?](https://stackoverflow.com/questions/10286514/why-is-googlemock-leaking-my-shared-ptr) ? – Yksisarvinen Jun 27 '19 at 08:22
  • Thank you all for pointing me to the right direction. You are right @sklott this was an issue with the owner of the mock object not being destroyed (see my answer). – pooya13 Jun 27 '19 at 18:55

1 Answers1

0

Thanks to @YSC, @sklott and @Yksisarvinen that pointed me to the right direction.

For anyone having a similar issue. It turned out that in my case the issue was unrelated to the Google C++ mocking framework. I was passing the mock object to a derived class, whose base class's destructor was not declared as virtual. Therefore the destructor of the mock owner was never called and the mock object was kept alive.

pooya13
  • 2,060
  • 2
  • 23
  • 29