Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gmock pass out parameter reference with deleted constructor

I am trying to reference an out argument of the mocked method getData. My problem is that "ControlData" has no copy constructor because it got deleted. As far as I understand, "SetArgReferee" does create an intermediate object before passing it by reference.

MOCK_METHOD1(getData, void(ControlData& par_rcl_ControlData));

ControlData loc_data;

EXPECT_CALL(loc_cl_control, getData(_)).WillOnce(SetArgReferee<0>(loc_data));

I have tried to create an custom action such as:

ACTION_P(SetArgRef, obj) { arg0 = &obj; }

But unfortunately this does not compile either. How can I pass an object directly on the mocked method?

like image 939
Pepelee Avatar asked Nov 20 '25 15:11

Pepelee


1 Answers

Quoting form GoogleMock Cook Book:

SetArgPointee() conveniently makes an internal copy of the value you pass to it, removing the need to keep the value in scope and alive. The implication however is that the value must have a copy constructor and assignment operator.

Presumably the same applies to SetArgReferee. This means you need a custom action to move the object into that reference (without using copy constructor at any place).

Fortunately, later on there is a suggestion:

but how do we work with methods accepting move-only arguments? The answer is that they work normally, although some actions will not compile when any of method's arguments are move-only. You can always use Return, or a lambda or functor:

What you need is a lambda (or any function object) that will pass argument by move:

ControlData loc_data;

auto SetArgByMove = [&loc_data](auto& arg){arg = std::move(loc_data);};
EXPECT_CALL(loc_cl_control, getData(_)).WillOnce(Invoke(SetArgByMove));

This should compile and run without issues.


You could probably make a custom action as well, but not via ACTION_P macro - it also creates a copy of the object. You would have to write fully fledged action by creating a class that inherits from ActionInterface

like image 194
Yksisarvinen Avatar answered Nov 23 '25 05:11

Yksisarvinen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!