13

Using GMock, how can I verify that a class's destructor is called? Is there a way, other than to wrap it in another class?

The obvious method, EXPECT_CALL(object, ~classtype()) yields a compiler error (gmock cannot produce a mock method called gmock_~classtype).

vegemite4me
  • 6,621
  • 5
  • 53
  • 79
Andres Jaan Tack
  • 22,566
  • 11
  • 59
  • 78

2 Answers2

23

An easy way to check for a destructor call:

class MockFoo : public Foo {
  ...
  // Add the following two lines to the mock class.
  MOCK_METHOD0(Die, void());
  virtual ~MockFoo() { Die(); }
};

In your test function:

 MockFoo* foo = new MockFoo;
  ...
  {
    EXPECT_CALL(*foo, Die());
  }

More Details can be found here: Mocking Destructors

nasso
  • 603
  • 5
  • 13
nabulke
  • 11,025
  • 13
  • 65
  • 114
4

Unless you're passing --gmock_catch_leaked_mocks=0, then gmock should already be detecting when you fail to destroy a mock. The destructor is where unsatisfied expectations are flagged as errors, so gmock has special support for detecting when it is not called.

sfiera
  • 109
  • 6
  • 1
    There's a caveat, though: GMock will *not* detect leaked mocks that doesn't have any expectations attached to them (ON_CALL / EXPECT_CALL). This is because leak check is based on information that is stored in special entity called GTest registry, and mocks without expectations are not registered in it. – r5ha Jun 30 '17 at 16:51