The Google Mock documentation says:
Important note: Google Mock requires expectations to be set before the mock func
Just as the documentation says, what is important is that expectations are set before the method is called. However, this does not mean
that it is not possible to interleave EXPECT_CALL and invocation of mock method. It's just that you have to clear the expectations on the mock object yourself. For example, assume that we have the following mock
class
class MyMock : public bravo::IRealClass
{
public:
...
MOCK_METHOD1(myMethod, bool(int));
...
}
Now, assuming that a call to method testMethod calls myMethod once, you can write something like this in a test:
TEST(FooTest, testCaseName)
{
MyMock myMockObj;
...
EXPECT_CALL(myMockObj, myMethod(_)).WillOnce(Return(true));
testMethod();
ASSERT_THAT(...);
// Explicitly clear expectations and set new ones.
Mock::VerifyAndClearExpectations(&myMockObj);
EXPECT_CALL(myMockObj, myMethod(_)).WillOnce(Return(false));
testMethod();
ASSERT_THAT(...);
}
This will be fine since the mock object can be reliably reused again. However, if you omit to explicitly clear the expectations, you are entering the realm of undefined behavior. As is always the case with undefined behavior, it is possible that it won't crash and it might even work in some cases, but if you have have something like that in your code you should definitely fix it.