Search code examples
c++googletestgooglemock

What happens if multiple WillRepeatedly actions are specified on a google mock?


I have this kind of test setup:

for (...)
{
    std::unique_ptr<MockObject> mock = std::make_unique<MockObject>();
    const SomeObject* validObject = ...;
    EXPECT_CALL(*mock, method(_)).WillRepeatedly(Return(validObject));
}

Is this guaranteed to return the validObject object local to the scope of the current for? If so, would it behave the same if the mock was declared outside the for?


Solution

  • For this example, each iteration of the for loop makes a new MockObject mock.

    The EXPECT_CALL....WillRepeatedly line will set the return value for this method of that mock object only to whatever validObject points to.

    would it behave the same if the mock was declared outside the for?

    Yes, at least this part of the test will. The difference is that the mock object will be shared between all iterations of the for loop and will hold its state betewen iterations, I'd double check that the test doesn't assume that each iteration of the loop is getting a new mock object.