In our application you should never obtain NOW via new DateTime()
or from SQL NOW()
. Because it's unmockable
and therefore untestable.
This ultra-simple library provides service you can easily use and mock.
composer install damejidlo/datetime-factory
And then just register it in your config.neon
as a service.
trait MockDateTimeFactoryTrait
{
/** @return Container */
abstract function getContainer();
private function mockDateTimeFactoryService(\DateTime $subjectTime)
{
$dateTimeFactory = Mockery::mock(DateTimeFactory::class);
$dateTimeFactory->shouldReceive('getNow')->andReturn($subjectTime);
$this->getContainer()->removeService('dateTimeFactory');
$this->getContainer()->addService('dateTimeFactory', $dateTimeFactory);
}
}