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 GetEntry
method invokes GetCurrentTime
call. I'd like to mock the GetCurrentTime method so that I can advance the clock in my test to test the aging out of entries which happens as part of the GetEntry
call (please don't ask me why the aging is being done as part of GetEntry
call... that's another discussion :( ). Here's my mock 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 run the test, I expected the mCurrentTime
value to be return by my mock GetCurrentTime
function. However, I get the following error output:
GMOCK WARNING:
Uninteresting mock function call - taking default action specified at:
..../test_local_cache.cpp:62:
Function call: GetCurrentTime()
Returns: 0
Stack trace:
Would appreciate it if someone can let me know what I am doing wrong and how to fix it. Thanks in advance.
The solution to your problem is to make it in much simpler way. Just use EXPECT_CALL
where 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();