Search code examples
googlemock

SetArgPointee with a variable


I have a mock with such methods:

MOCK_METHOD2(setValue, int(int notImportant, unsigned int value));
MOCK_METHOD2(getValue, int(int notImportant, unsigned int *value));

Methods can be called several times throughout the test, so it's important to store the values being set (and to pass the latest one when requested).

I tried to then mock this behaviour:

unsigned int myStoredValue;
ON_CALL(ddalCpriLink, setValue(_, _))
    .WillByDefault(DoAll(SaveArg<1>(&myStoredValue),
        Return(RETURN_OK)));
ON_CALL(ddalCpriLink, GetValue(_, _))
    .WillByDefault(DoAll(SetArgPointee<1>(myStoredValue),
        Return(RETURN_OK)));

This is where problem comes out. SetArgPointee<> does not pass the value stored in myStoredValue, it simply sets given variable to 0. In theory, it would be possible to use direct values, but it makes testing unreasonable (what if set is not called properly?). The other option is to just pass a function doing so with Invoke(), but I'd rather stick to gmock solutions if possible.

My question is: Is it possible to pass value of variable to SetArgPointee<>? If not, is there any particular reason googletest team decided to not implement such feature?


Solution

  • If you extend your code with ByRef it works:

    ON_CALL(ddalCpriLink, GetValue(_, _))
        .WillByDefault(DoAll(SetArgPointee<1>(ByRef(myStoredValue)),
            Return(RETURN_OK)));
    

    If you don't use ByRef the value of myStoredValue is used, when the line is executed.