Pass method parameter to an action in googlemock
-
08-12-2019 - |
سؤال
I use Gmock for a method call, that returns an element of the QList heightsFromCsvResult as out parameter. Here is the currently working code:
EXPECT_CALL(*_mockAttributeRepository, getGeometryHeightValues(_,_))
.WillOnce(DoAll(SetArgReferee<1>(heightsFromCsvResult.at(0)), Return(true)))
.WillOnce(DoAll(SetArgReferee<1>(heightsFromCsvResult.at(1)), Return(true)))
.WillOnce(DoAll(SetArgReferee<1>(heightsFromCsvResult.at(2)), Return(true)))
.WillOnce(DoAll(SetArgReferee<1>(heightsFromCsvResult.at(3)), Return(true)));
The first parameter lineNumber from
getGeometryHeightValues(int lineNumber, QPair<QString, QString>)
is the index for heightsFromCsvResult.at(lineNumber).
Now I try to use Gmock in a more generic way:
int* mockLineNumber = new int;
EXPECT_CALL(*_mockAttributeRepository, getGeometryHeightValues(_,_))
.Times(4)
.WillRepeatedly(DoAll(SaveArg<0>(mockLineNumber), SetArgReferee<1>(heightsFromCsvResult.at(*(mockLineNumber))), Return(true)));
But this code does not work, because mockLineNumber is never written by Gmock. But the EXPECT_CALL is satisfied.
Does anyone see the problem in the code?
المحلول
Using a variable set with SaveArg within the same EXPECT_CALL does not seem to be working, what you could do instead is to go through a custom action that sets the second argument using argument 0 as index on the passed container.
ACTION_P(SetArg1WithValueFromPassedArgumentUsingArg0AsIndex, param)
{
arg1 = param.at(arg0);
}
int* mockLineNumber = new int;
EXPECT_CALL(*_mockAttributeRepository, getGeometryHeightValues(_,_))
.Times(4)
.WillRepeatedly(DoAll(SaveArg<0>(mockLineNumber), SetArg1WithValueFromPassedArgumentUsingArg0AsIndex(heightsFromCsvResult), Return(true)));
Unless you need mockLineNumber for something else you could remove that part.