Skip to content

Commit a103731

Browse files
Moroine Bentefritjaviereguiluz
Moroine Bentefrit
authored andcommitted
Add details on how the ClockMock::register works
1 parent 4bbe654 commit a103731

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

components/phpunit_bridge.rst

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,54 @@ test::
232232

233233
And that's all!
234234

235+
.. caution::
236+
237+
The ``@group time-sensitive`` annotation is equivalent to ``ClockMock::register(MyTest::class)``,
238+
so if you want to get a time-based function mocked into another class you will need to
239+
add it explicitly using ``ClockMock::register(MyClass::class)``. The ``ClockMock::register`` method
240+
creates a mock of the time based functions into the same namespace as your class. So when using
241+
``time()`` you will use the mock instead of the default one::
242+
243+
namespace App;
244+
245+
class MyClass
246+
{
247+
public function getTimeInHours()
248+
{
249+
return time() / 3600;
250+
}
251+
}
252+
253+
.. code-block:: php
254+
255+
namespace App\Tests;
256+
257+
use App\MyClass;
258+
use PHPUnit\Framework\TestCase;
259+
260+
/**
261+
* @group time-sensitive
262+
*/
263+
class MyTest extends TestCase
264+
{
265+
public function testGetTimeInHours()
266+
{
267+
ClockMock::register(MyClass::class);
268+
269+
$my = new MyClass();
270+
271+
$result = $my->getTimeInHours();
272+
273+
$this->assertEquals(time() / 3600, $result);
274+
}
275+
}
276+
277+
.. caution::
278+
279+
Keep in mind that mocking is done by using the namespace resolutions rules
280+
(http://php.net/manual/en/language.namespaces.rules.php). So time-based functions need to be used as
281+
"Unqualified name", i.e. ``\time()`` cannot be mocked.
282+
235283
.. tip::
236284

237285
An added bonus of using the ``ClockMock`` class is that time passes

0 commit comments

Comments
 (0)