GMock: how to return a mock class variable as return value

I am trying to use GMock (Google Mocking Framework for c ++) for the first time. I have the following class:

class LocalCache
{
public:
  virtual time_t GetCurrentTime() = 0;
  virtual int AddEntry(const std::string key, std::string& value);
  virtual int GetEntry(const std::string key, std::string& value);
};

The method GetEntrycalls GetCurrentTime. I would like to simulate the GetCurrentTime method so that in the test you can increase the time to test the aging of records that occurs as part of the call GetEntry(please do not ask me why aging is performed as part of the call GetEntry... this is another discussion :(). Here my false class:

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

  MockLocalCache()
  : mCurrentTime(0)
  {
  }

  void EnableFakeTime()
  {
    ON_CALL(*this, GetCurrentTime()).WillByDefault(Return(mCurrentTime));
  }

  void SetTime(time_t now) { mCurrentTime = now; }

private:
  time_t  mCurrentTime;
};

TEST(MockTest, TimeTest)
{
  MockLocalCache mockCache;

  mockCache.EnableFakeTime();

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

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

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

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

When I ran the test, I expected the value to mCurrentTimebe returned by my dummy function GetCurrentTime. However, I get the following error message:

GMOCK WARNING:
Uninteresting mock function call - taking default action specified at:
..../test_local_cache.cpp:62:
    Function call: GetCurrentTime()
          Returns: 0
Stack trace:

, - , . .

+6
2

, . EXPECT_CALL, :

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));
}

, , - - - :

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

google-mock-doc Return Return(ByRef...

- , set member, , , , , EXPECT_CALL:

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

( , ), PiotrNycz - , ( ) - . "" .

; :

  • Return(field) ( )
  • Return(ByRef(field)) ( , , , )
  • ReturnRef(field) ( )
  • ReturnPointee(&field) ( )

, , pointee , , .

0

Source: https://habr.com/ru/post/1607041/


All Articles