c++unit-testinggoogletestgooglemock

Return alternating values from mock


I want to test a function where one of its mocks should return alternating values many times. So e.g. I need something like this:

EXPECT_CALL(my_mock, foo(_))
    .WillOnce(Return(A))
    .WillOnce(Return(B))
    .WillOnce(Return(A))
    .WillOnce(Return(B))
    .WillOnce(Return(A))
    .WillOnce(Return(B))
    // repeated forever / many times

Is there an elegant way to specify this in gmock without needing to copy & paste the WillOnce statements as often as they will be called by the SUT?


Solution

  • Since GoogleMock 1.11.0 there is a built-in Action ReturnRoundRobin() which does exactly what you want:

    EXPECT_CALL(my_mock, foo(_))
        .WillRepeatedly(ReturnRoundRobin({A, B}));
    

    See it online


    Before GoogleMock 1.11, I guess the easiest option is using a lambda with static counter:

    EXPECT_CALL(my_mock, foo(_))
        .WillRepeatedly(InvokeWithoutArgs([](){
            static int counter = 0;
            constexpr static std::array<int, 2> values {13, 26};
            return values[counter++ % values.size()];
        }));