如何正确地使模拟方法调用原始虚方法

How to correctly make mock methods call original virtual method

我想为模拟方法定义在测试中调用它时的行为,所有特定于该测试的 EXPECTED_CALLON_CALL 都被检查,但仍然是原始方法之后正在执行。

您可以根据 Google Mock documentation:

使用委派到真实的技术来完成此操作

You can use the delegating-to-real technique to ensure that your mock has the same behavior as the real object while retaining the ability to validate calls. Here's an example:

using ::testing::_;
using ::testing::AtLeast;
using ::testing::Invoke;

class MockFoo : public Foo {
 public:
  MockFoo() {
    // By default, all calls are delegated to the real object.
    ON_CALL(*this, DoThis())
        .WillByDefault(Invoke(&real_, &Foo::DoThis));
    ON_CALL(*this, DoThat(_))
        .WillByDefault(Invoke(&real_, &Foo::DoThat));
    ...
  }
  MOCK_METHOD0(DoThis, ...);
  MOCK_METHOD1(DoThat, ...);
  ...
 private:
  Foo real_;
};
...

  MockFoo mock;

  EXPECT_CALL(mock, DoThis())
      .Times(3);
  EXPECT_CALL(mock, DoThat("Hi"))
      .Times(AtLeast(1));
  ... use mock in test ...