26
loading...
This website collects cookies to deliver better user experience
Carbon|CarbonImmutable
objects. In simple words, you can just do a Carbon::setTestNow($now)
to freeze the current time (or use the stateless counterpart Carbon::withTestNow($now, $closure)
).Service::doSomething
method, because I wanted to simulate use of 3rd party code outside of our control that thus cannot be changed to use Carbon.Service::doSomething
, we still cannot test that scenario.date()
, time()
, DateTime
, …) will still use the actual system clock, so it’s impossible to force code outside of your control to use your mocked date and time.Carbon
(instead of sticking with the standard DateTime). This is not necessarily an issue, but it becomes relevant if you, like us, strive to keep exposure of your business logic to 3rd party libraries to the minimum.\timecop_freeze($date)
in your test code to bring the system clock to that specific moment. You then use \timecop_return()
(still in your test code) when you want to go back to the actual system clock.\DateTime
and \DateTimeImmutable
with the ones of mock classes that consider the aforementioned mockable clock.ClockInterface
service that provides a way to obtain the current time (I also learned there’s a proposed standard for it). This way, the current time would be mockable like any other service.\DateTime
or a timestamp from a 3rd party library and that would “escape” your ClockInterface
service (in case it’s impossible to make it interoperate with said library).\DateTime
objects right inside entities (in constructor or mutator methods) it would be cumbersome having to pass a Clock from the outside every time. Sometimes, use of dates could even be a private implementation detail — having to pass a clock service from the outside would leak this detail unnecessarily and make the public interface more complex.executeAtFrozenDateTime
). It works with PHP 8 already, and the good thing is that the uopz extension is well maintained, so ClockMock is here to stay. We encourage you to use it and report any issues or feedback you may have.