Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly make mock methods call original virtual method

Tags:

c++

googlemock

I want to define for a mocked method the behavior that when it is called in a test, all the EXPECTED_CALL and ON_CALL specific for that test are being checked, but still the original method is being executed after that.

like image 433
nyarlathotep108 Avatar asked Jan 24 '26 08:01

nyarlathotep108


1 Answers

You can accomplish this by using the delegating-to-real technique, as per 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 ...
like image 129
frslm Avatar answered Jan 25 '26 20:01

frslm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!