GMock:如何 return 模拟 class 变量作为 return 值

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

我是第一次尝试使用 GMock(google c++ 模拟框架)。我有以下 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);
};

GetEntry 方法调用 GetCurrentTime 调用。我想模拟 GetCurrentTime 方法,以便我可以在我的测试中提前时钟来测试作为 GetEntry 调用的一部分发生的条目的老化(请不要问我为什么老化正在发生作为 GetEntry 电话的一部分完成...那是另一个讨论 :( )。这是我的模拟 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));
}

当我 运行 测试时,我希望我的模拟 GetCurrentTime 函数的 mCurrentTime 值是 return。但是,我得到以下错误输出:

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

如果有人能让我知道我做错了什么以及如何解决它,我将不胜感激。提前致谢。

您的问题的解决方案是以更简单的方式解决问题。只需在您希望调用模拟函数的地方使用 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 中查找 ReturnReturn(ByRef 之间的区别...

可能 - 我没有检查这个,调用设置成员值,在调用设置这个默认值之前也可以工作 - 但正如我所说 - 对于你的情况,应使用 EXPECT_CALL:

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

仅作记录(未来的人会像我一样发现这个问题),而 是您可以做到的最佳选择(将测试值直接保存在测试中)——在某些情况下return "live" return 来自字段或变量的值确实是必要的。

相应的文档是 here;特别是:

  • Return(field) 不起作用(它在定义操作时复制字段的当前值)
  • Return(ByRef(field)) 不起作用(它的作用与上面完全相同,与您的预期相反)
  • ReturnRef(field) 不编译(因为 return 类型不是引用)
  • ReturnPointee(&field) 有效(它 return 是实际调用方法时的值)

当然,无论何时调用该方法,您都必须确保指针保持有效,因为它现在被直接使用,而不是复制。