Search code examples
c++callbackgoogletest

Saving function arguments to a mock method from a EXPECT_CALL


I have a class that "subscribes" to a signal from a component by calling subscribe(callbackfunction). I am now trying to test this behaviour with gtest/gmock by saving the callback and send data to it later to test other parts of that component.

gtest code:

using callback = std::function<void(const int*)>;
callback cb;

EXPECT_CALL(*mock_data, Subscribe).WillOnce(SaveArg<0>(cb));

gmock code (mock_data):

MOCK_METHOD(bool, Subscribe, (std::function<void(const int*)> cb), (const));

And I am getting this from the compiler:

error: cannot convert ‘testing::internal::SaveArgAction<0, std::function<void(const int*)> >’ to ‘const testing::Action<bool(std::function<void(const int*)>)>&’

Is there a way to actually do what I want to do?


Solution

  • SaveArg<N>(pointer) expects a location/pointer where to store an argument.

    EXPECT_CALL(*mock_data, Subscribe).WillOnce(SaveArg<0>(&cb));