Search code examples
c++c++11googletestgooglemock

GMock, invoking std::function captured by SaveArg


std::function<result(xxx &, yyy)> l_function;
auto l_strategyMock = std::make_shared<StrategyMock>();
EXPECT_CALL(*m_strategyFactoryMock, createStrategy("default", _))
            .WillRepeatedly(DoAll(SaveArg<1>(&l_function),
                                  Return(l_strategyMock)));
EXPECT_CALL(*l_strategyMock, invokeFunction(_, _)) //invokeFunction(xxx &, yyy)
            .WillOnce(Invoke(l_defaultHoStartRequestFiller));

this code crashes with:

C++ exception with description "bad_function_call" thrown in the test body.

First function is invoked with lambda as parameter<1>. I want to capture it and then call it on second EXPECT_CALL, but l_function seems not initialized.

Is there something like "InvokePointee" to make this work?


Solution

  • Use std::reference_wrapper<T>. It provides a function call operator, and itself is a copyable type:

    EXPECT_CALL(*l_strategyMock, invokeFunction(_, _))
            .WillOnce(Invoke( std::ref(l_function) ));
    //                        ~~~~~~~~^          ^