Reputation: 4097
I have a piece of C++ code in C++11 that uses localtime
function (doc) to get the time. If the day is my birthday, it returns a birthday message.
std::string message = getDailyMessage();
I would now like to make a unit test that determines if the code outputs the right value on my birthday and not on my birthday. Is there a way to programmatically set the value returned by localtime
before two adjacent calls? Is it possible to do without mucking around with the actual system time?
setTime(NOT_BIRTHDAY);
EXPECT_STREQ(NOT_BIRTHDAY_MESSAGE, getDailyMessage());
setTime(BIRTHDAY);
EXPECT_STREQ(BIRTDAY_MESSAGE, getDailyMessage());
Upvotes: 1
Views: 358
Reputation: 75755
You could make getDailyMessage
take the time by parameter. This makes unit testing a breeze and adds the flexibility of being able to use it in other contexts. For instance you could use it to print the yesterday's message.
Upvotes: 3