Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GMock: Capture a reference argument in a mocked function

I have a mocked function that has a reference argument:

MOCK_METHOD(func, void(MyObj &obj);

I'd like to capture obj into a variable so that I can call methods on it in the unit tests. So something like:

MyObj *capturedObj;
EXPECT_CALL(foo, func(testing::_)).WillOnce(<capture arg into capturedObj>);
capturedObj->bar();

How do I achieve this?

like image 278
gw111zz Avatar asked Sep 11 '25 05:09

gw111zz


1 Answers

One possible way to do that is to invoke a separate test function that will capture the argument(s) for you.

This can be done with the Invoke() action, as described in the documentation:

Invoke(f) Invoke f with the arguments passed to the mock function, where f can be a global/static function or a functor.

Invoke(object_pointer, &class::method) Invoke the method on the object with the arguments passed to the mock function.

In your case, something like the following code should work:

// Globally, outside your test case
MyObj *capturedObj;

void captureObj(MyObj &obj) {
    captured = &obj;
}

// [..]

// In your test case
EXPECT_CALL(foo, func(testing::_)).WillOnce(testing::Invoke(captureObj));
capturedObj->bar();

If you use test fixtures, capturedObj and captureObj can be class members, and you need to update the syntax as follows:

  EXPECT_CALL(foo, func(testing::_)).WillOnce(testing::Invoke(this, &TestFixtureClass::captureObj));
like image 175
AntonyG Avatar answered Sep 13 '25 21:09

AntonyG