Ambrosius Topor

Notiz — 2020-05-03

Testing Time

If you are using the current date/time in your code, using the DateTime class (or similar) chances are, you will face difficulties when it comes to testing.

You could adjust your test data everytime you run your tests—but that doesn't sound neither right nor performant (not to mention the effort if you have a large test data setup).

To avoid running into problems you can get the current date in a different approach; one being providing it by a container:

// Setup for production environment
$container['now'] = function () {
    return function () {
        return new DateTime();
    };
};

While it is working nice for the real code in production, getting the most up-to-date current time in a testing context might cause trouble.

In such a scenario it would be more beneficial to retrieve the current date when starting the application and refer back to this same value throughout the test run:

// Setup for development/testing environment
$container['now'] = function () {
    $now = new DateTime('2020-05-01T12:00:00');
    return function () use ($now) {
        return $now;
    };
};

This structure makes it possible to use the same code in the application:

$dateNow = $this->container->get('now')();

Comments

There are no comments yet.

Thanks for your contribution!
Your comment will be visible once it has been approved.

An error occured—please try again.

Add Comment