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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With