Search code examples
c++unit-testinggoogletest

Google test save one argument into another argument


Is possible to save one argument from a mock function call into another ? for instance argument 1 into argument 4 ?

EXPECT_CALL(mock_, up_func(_, _, _, _)).
.WillOnce(DoAll(SaveArg<1>(Argument4), Return(LSUCCESS)));

Solution

  • You can do that either with Invoke

    EXPECT_CALL(mock_, up_func(_, _, _, _))
    .WillOnce(
        WithArgs<0, 3>(
            Invoke([](auto in, auto& out){out = in; return LSUCCESS;})
        )
     );
    

    Or using a helper variable

    int helper;
    EXPECT_CALL(mock_, up_func(_, _, _, _))
    .WillOnce(
        DoAll(
            SaveArg<0>(&helper),
            SetArgReferee<3>(ByRef(helper)),
            Return(0)
        )
     );
    

    Note: ByRef is important, otherwise you will get copy of the value of helper from the moment when expectation was set, not the value set later by SaveArg.

    A third option would be to define a custom action if this is something you will be using a lot. Custom action could be used with WithArgs to select arguments (simpler version) or templated to avoid WithArgs everytime (harder).

    See it online