Interleaving EXPECT_CALL()s and calls to the mock functions

前端 未结 2 877
攒了一身酷
攒了一身酷 2021-01-18 12:31

The Google Mock documentation says:

Important note: Google Mock requires expectations to be set before the mock func

2条回答
  •  一个人的身影
    2021-01-18 13:20

    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.

提交回复
热议问题