If possible, how do you mock the time for the purpose of triggering boost timers in a unit test?
For example, is it possible to achieve something like the following:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
void print(const boost::system::error_code& /*e*/)
{
std::cout << "Hello, world!\n";
}
int main()
{
boost::asio::io_service io; // Possibly another class needed here, or a way of setting the clock to be fake
boost::asio::deadline_timer t(io, boost::posix_time::hours(24));
t.async_wait(&print);
io.poll(); // Nothing should happen - no handlers ready
// PSEUDO-CODE below of what I'd like to happen, jump ahead 24 hours
io.set_time(io.get_time() + boost::posix_time::hours(24));
io.poll(); // The timer should go off
return 0;
}
Update Thank you to all the answers, they have provided excellent insight into the problem. I have provided my own answer (SSCCE), but couldn’t have done that without the help provided.
A SSCCE, based on a link posted by @free_coffee:
Thankyou to @free_coffee for providing this link to a blog entry from the creator of boost asio. The above is slightly modified (and I believe slightly improved). By not using an offset on the system clock, you gain complete control over the timers: they will not fire until you explicitly set time forward past the timer.
The solution could be improved by making the
this_thread::sleeppart configurable. Note that theto_posix_durationhack described in [1] needs to use a smaller duration than thesleep.To me this approach still seems a bit magic, since the
time_traitsare not well documented, and in particular the hack ofto_posix_durationhas a whiff of voodoo about it. I guess it just comes down to intimate knowledge of thedeadline_timerimplementation (which I don’t have).