c++mockinggoogletest

gtest: Invoke an argument's member function


Let's suppose I have this piece of code that I am testing with gtest:

struct MyStruct {
    std::function<void(const std::string&)> myLambda;
    std::string myString;
};

void MyClass::post(MyStruct myStruct)
{
    // Do something.
    // Call myStruct.myLambda on some scenarios.
}

How could I invoke myStruct.myLambda from an EXPECT_CALL() macro? I mean, something like this:

MockMyClass mockMyClass;
EXPECT_CALL(mockMyClass, post(testing::_)).WillOnce(Invoke(GetArgument(0).myLamda);

Note that GetArgument is an invented method that returns the first argument of the mocked method, that is, a MyStruct instance.


Solution

  • There is no built-in action that would do that, you have to write your own:

    EXPECT_CALL(mockMyClass, post(testing::_)).WillOnce(Invoke([](MyStruct m){ m.myLambda("some string"); }));
    

    If you want to reuse it, you can define any callable (function or functor) or create an Action with macro:

    ACTION_P(CallMyLambda, someString) {
        arg0.myLambda(someString);
    }
    

    and use it with

    EXPECT_CALL(mockMyClass, post(testing::_)).WillOnce(CallMyLambda("myString"));