1

Code

class A {
 public:
  void doit() {...}
}

class B {
 public:
  explicit B(unique_ptr<A> a): a_(move(a)) {}

  void run() {
    a_->doit();
  }

 private:
  unique_ptr<A> a_;
}

Test Code

class MockA : public A {
 public:

  MOCK_METHOD0(doit, void(void));
}

TEST(BTest, Test) {
  auto mockA = std::make_unique<A>();
  EXPECT_CALL(*mockA, doit(_)).Times(1);

  B b(std::move(mockA));
  b.run();
}

When running this code it leaks

ERROR: this mock object (used in test BTest.Test) should be deleted but never is. Its address is @0x1234.

Since expectations are supposed to run during destruction I am not sure why its causing issues.

I tried shared_ptr alias method as described here - Dependency injection with unique_ptr to mock but even still I get that exception.

Community
  • 1
  • 1
jack_carver
  • 1,510
  • 2
  • 13
  • 28

1 Answers1

2

The class A needs to have virtual destructor, otherwise destructor for class MockA is not executed.

BЈовић
  • 62,405
  • 41
  • 173
  • 273