Write Time-Sensitive Test in Symfony 7

Write Time-Sensitive Test in Symfony 7

The Clock component, provided by Symfony, allows handling tasks related to time management. This component is very useful to test time-sensitive code. It could include scenarios like scheduled tasks, event triggers, or anything where time plays a significant role in the expected outcome. This tutorial shows how to write a time-sensitive test in Symfony 7.

Consider a scenario where we have a controller designed to provide a response containing the present date and time. Utilizing the ClockAwareTrait, this controller makes use of the now method to retrieve the current date and time information.

src/Controller/DateTimeController.php

<?php

namespace App\Controller;

use Symfony\Component\Clock\ClockAwareTrait;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class DateTimeController
{
    use ClockAwareTrait;

    #[Route('/now')]
    public function index(): Response
    {
        return new Response($this->now()->format('Y-m-d H:i:s'));
    }
}

The Clock component offers an additional trait, known as ClockSensitiveTrait, facilitating the creation of tests that are sensitive to time-related scenarios. This trait equips you with methods for freezing time during tests and subsequently restoring the global clock to its normal state after each test execution.

Utilizing the mockTime method from the ClockSensitiveTrait allows us to engage with the simulated clock during testing scenarios.

The following code illustrates how to test a previously provided controller:

tests/Controller/DateTimeControllerTest.php

<?php

namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Clock\Test\ClockSensitiveTrait;

class DateTimeControllerTest extends WebTestCase
{
    use ClockSensitiveTrait;

    public function testIndex(): void
    {
        $now = '2023-12-30 10:51:30';
        static::mockTime($now);

        $client = static::createClient();
        $client->request('GET', '/now');

        self::assertSame($now, $client->getResponse()->getContent());
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.