Can changes made to references returned by Google Mock be reflected in the original value?

StackOverflow https://stackoverflow.com/questions/16311748

  •  13-04-2022
  •  | 
  •  

Question

Can changes made to references returned by Google Mock be reflected in the original value?

Sample test code (using CppUnit as the unit testing framework):

int i = 0;
EXPECT_CALL(mock, GetValue())
    .WillOnce(ReturnRef(i));

...

CPPUNIT_ASSERT_EQUAL( 1, i );

Sample code:

auto x = obj.GetValue();
++x;

My testing shows that this doesn't update the value of i, but Google's description of ReturnRef and ReturnRefOfCopy seems to mean that this should work, i.e.

  • ReturnRef(variable) - Return a reference to variable.
  • ReturnRefOfCopy(value) - Return a reference to a copy of value; the copy lives as long as the action.

Instead it seems like ReturnRef also returns the reference to a copy. Is there some way to get this behaviour using Google Mock?

Was it helpful?

Solution

auto uses the same type deduction rules as templates. In your case auto x means the same as a template type parameter.

template<typename T>
int function(T t) { 
    T x; // <-- is equivalent to `auto x` outside of a template
};

In your example the type is deduced to an int rather than int& as you were expecting which is why the original value remained the same. You will need to declare the reference explicitly (auto& x) in order to modify the original value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top