GMock: How to return mock class variable as the return value

The solution to your problem is to make it in much simpler way. Just use EXPECT_CALLwhere you expect call to your mocked function:

class MockLocalCache : public LocalCache
{
public:
  MOCK_METHOD0(GetCurrentTime, time_t());
};

TEST(MockTest, TimeTest)
{
  MockLocalCache mockCache;

  std::string key("mykey");
  std::string value("My Value");

  EXPECT_TRUE(mockCache.AddEntry(key, value));

  EXPECT_CALL(mockCache, GetCurrentTime()).WillOnce(Return(10));   // advance 10 seconds

  std::string expected;
  EXPECT_TRUE(mockCache.GetEntry(key, expected));
}

Just to answer why your example did not work - with this call, the current value of your member variable is stored - later change to it has no effect:

ON_CALL(*this, GetCurrentTime()).WillByDefault(Return(mCurrentTime));

Look in google-mock-doc for difference between Return and Return(ByRef...

Probably - I did not check this, calling set member value, before calling setting this default would also work - but as I said - for your case EXPECT_CALL shall be used:

 mockCache.SetTime(10);   // advance 10 seconds
 mockCache.EnableFakeTime();

Just for the record (and future people finding this question, like me), while PiotrNycz's answer is the best option when you can do it (keeping test values directly within tests) -- in some cases it really is necessary to return a "live" return value from a field or variable.

The appropriate documentation is here; in particular:

  • Return(field) doesn't work (it makes a copy of the field's current value when the action is defined)
  • Return(ByRef(field)) also doesn't work (it does exactly the same as above, contrary to what you might expect)
  • ReturnRef(field) doesn't compile (because the return type isn't a reference)
  • ReturnPointee(&field) does work (it returns the value as of the time the method is actually called)

Of course, you have to ensure that the pointee remains valid whenever the method is called, since it's now being used directly instead of making a copy.