Search code examples
phpunit-testingsymfonymockingphpunit

Symfony Testing - ClockMock / DateTime


I looking for help with creating complex test for our JSON API based application.

Short problem scenario:

  • Test create temporary entity (for compare)
  • EntityManagerMock is set to wait for persist($temporaryEntity)
  • Test call real method with some parameters
  • Method create entity and try to save at mocked EM
  • Test fails because time change for 1 second

enter image description here

We tried to use ClockMock but it's work only for class where was called/for namespace. Our method is at other namespace and entity is created in some next.

We looking for solution how to temporary override PHP platform \DateTime class - or technique how to use ClockMock for all namespaces/class in project (but only for tests). We tried to modify Symfony based ClockMock - but good way not found :-/.

Is there any way? (I dont want use something like get_declared_class() and call with it clockMock::register - because it's very slow soloution for about 15.000 tests :-/.

Thanks all!


Solution

  • The ClockMock doesn't work for new \DateTime() but only on time-based PHP function.

    From the announcement of the features:

    This means that you don't need to make a single change in your original code, except when using new DateTime(), which must be replaced by DateTime::createFromFormat('U', time()) to use the mocked time() function.

    So try as suggested: replace any DateTime object creation with the named-constructor with the time function.

    Hope this help