Search code examples
c++mockinggooglemock

Can you specify expectations in mocked class constructor in GMock?


I want to create a Mock Class that will have some default characteristics on its mocked methods ie:

struct SuperMock {
  SuperMock() {
    ON_CALL(*this, mockedMethod1).WillByDefault(Return(1));
    ON_CALL(*this, mockedMethod2).WillByDefault(Return(2));
  }
  MOCK_CONST_METHOD(mockedMethod1, int());
  MOCK_CONST_METHOD(mockedMethod2, int());
};

Is that legal? Will it work properly?


Solution

  • Yes, you can do that. See such usage in the example on the official guide page:

    class MockFoo : public Foo {
     public:
      MockFoo() {
        // By default, all calls are delegated to the real object.
        ON_CALL(*this, DoThis).WillByDefault([this](int n) {
          return real_.DoThis(n);
        });
        ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) {
          real_.DoThat(s, p);
        });
        ...
      }
      MOCK_METHOD(char, DoThis, ...);
      MOCK_METHOD(void, DoThat, ...);
      ...
     private:
      Foo real_;
    };