Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Mocking fixed absolute time

The Test::MockTime module has a number of ways to change the time:

  • We can set_absolute_time to any time, but after the setting the clock will move forward at its regular pace.
  • We can set_fixed_time to any time and the clock will not move forward.

These are useful when testing the behaviour of some code at a specific given date or time.

  • We can set_relative_time for things where the elapsed time is important. e.g. checking a timeout mechanism.
use strict;
use warnings;

use Test::MockTime qw(set_absolute_time restore_time set_fixed_time);
use Test::More;

use MyDaily qw(message);

diag "Normal time: ", time;

# Sets the clock that will move forward at a normal pace
set_absolute_time('1970-03-01T03:00:00Z');
diag "Absolute time: ", time;
is message(), 'Welcome to Perl';
sleep(2);
diag "Time moves forward: ", time;

# Sets the clock that will be fixed on that second
set_fixed_time('1970-04-01T03:00:00Z');
is message(), 'Welcome to Python';
diag "Fixed time: ", time;
sleep(2);
diag "Time is fixed: ", time;

restore_time();
diag "Back to now: ", time;

done_testing;