4

It's very clear from the docs that interleaving EXPECT_CALL() and calls to the mock function is undefined behavior in gmock, and it gets reiterated quite a bit (see e.g. Interleaving EXPECT_CALL()s and calls to the mock functions).

The documentation, however, specifically calls out EXPECT_CALL():

Important note: gMock requires expectations to be set before the mock functions are called, otherwise the behavior is undefined. In particular, you mustn't interleave EXPECT_CALL()s and calls to the mock functions.

Does this warning also apply to using ON_CALL()?

The general problem I face is that we're very frequently passing mock objects to the constructor of a uut in a test fixture, and sometimes the constructors actually need to use those mocks to initialize the uut to a specific state, so that we can then write a bunch of tests which verify the behavior when the object is in that state.

To illustrate the situation:

class MyFixture : public testing::Test {
 public:
  NiceMock<MyMock> mock;
  std::unique_ptr<MyUut> uut;
  MyFixture() {
    ON_CALL(mock, Something()).WillByDefault(Return(MyMock::SOME_VALUE));

    // constructor uses mock->Something() to initialize.
    uut = std::make_unique<MyUut>(&mock);

    // are we in UB-land?
  }
};

TEST_F(MyFixture, InvokesFooWhenDoingSomething) {
   EXPECT_CALL(mock, Foo());
   uut->DoSomething();
}
Quarra
  • 2,527
  • 1
  • 19
  • 27
josaphatv
  • 633
  • 4
  • 19
  • Isn't calling a virtual function in constructors isn't a bad practice? – Luca Mar 19 '21 at 21:16
  • 2
    @Luca Many people consider calling a class's *own* virtual functions during construction bad practice. I've never heard of calling the virtual functions of *other* objects being an issue. – josaphatv Mar 19 '21 at 21:18

0 Answers0