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();
}