GSP
Quick Navigator

Search Site

Unix VPS
A - Starter
B - Basic
C - Preferred
D - Commercial
MPS - Dedicated
Previous VPSs
* Sign Up! *

Support
Contact Us
Online Help
Handbooks
Domain Status
Man Pages

FAQ
Virtual Servers
Pricing
Billing
Technical

Network
Facilities
Connectivity
Topology Map

Miscellaneous
Server Agreement
Year 2038
Credits
 

USA Flag

 

 

Man Pages
Test::MockDateTime(3) User Contributed Perl Documentation Test::MockDateTime(3)

Test::MockDateTime - mock DateTime->now calls during tests

version 0.02

    use Test::More;
    use Test::MockDateTime;
    use DateTime;
    
    on '2013-01-02 03:04:05' => sub {
        # inside this block all calls to DateTime::now 
        # will report a mocked date.
        
        my $now = DateTime->now;
        is $now->ymd, '2013-01-02', 'occured now';
    };
    
    done_testing;

Getting the current time sometimes is not very helpful for testing scenarios. Instead, if you could obtain a known value during the runtime of a testcase will make your results predictable.

Why another Date Mocker? I wanted something simple with a very concise usage pattern and a mocked date should only exist and stay constant inside a scope. After leaving the scope the current time should be back. This lead to this tiny module.

This simple module allows faking a given date and time for the runtime of a subsequent code block. By default the "on" keyword is exported into the namespace of the test file. The date to get mocked must be in a format that is recognized by DateTime::Format::DateParse.

    on '2013-01-02 03:04:05', sub { ... };

is basically the same as

    {
        my $now = DateTime::Format::DateParse->parse_datetime(
            '2013-01-02 03:04:05'
        );
        
        local *DateTime::now = sub { $now->clone };
        
        ... everything from code block above
    }

A drawback when relying on this module is that you must know that the module you are testing uses "DateTime->now" to obtain the current time.

mocks date and time and then executes code

This module only mocks calls to "DateTime->now". All other ways to obtain a current time are not touched.

There are some alternatives. Depending on the environment you might consider using one of them instead.
Test::MockTime
Very universal, overwrites several subs at compile time and allows to set a fixed or ticking time at any place in your code.
Time::Mock
Also allows to set a time at various places inside your code.
Test::MockTime::DateCalc
Mocks serveral Date::Calc functions.
Time::Fake
Also overwrites several subs at compile time.

Wolfgang Kinkeldei, <wolfgang@kinkeldei.de>

This library is free software. You can redistribute it and/or modify it under the same terms as Perl itself.
2013-10-01 perl v5.32.1

Search for    or go to Top of page |  Section 3 |  Main Index

Powered by GSP Visit the GSP FreeBSD Man Page Interface.
Output converted with ManDoc.