8000 minor #8899 Add details on how the ClockMock::register works (moroine) · symfony/symfony-docs@49bacc7 · GitHub
[go: up one dir, main page]

Skip to content

Commit 49bacc7

Browse files
committed
minor #8899 Add details on how the ClockMock::register works (moroine)
This PR was squashed before being merged into the 2.8 branch (closes #8899). Discussion ---------- Add details on how the ClockMock::register works Hi, I got some trouble mocking using the ClockMock feature. After dig into the code, I figure myself how it works ! So I decided to do a PR, but I'm not sure of the formatting, Commits ------- a103731 Add details on how the ClockMock::register works
2 parents 79759c3 + a103731 commit 49bacc7

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
@@ -288,6 +288,54 @@ test::
288288

289289
And that's all!
290290

291+
.. caution::
292+
293+
The ``@group time-sensitive`` annotation is equivalent to ``ClockMock::register(MyTest::class)``,
294+
so if you want to get a time-based function mocked into another class you will need to
295+
add it explicitly using ``ClockMock::register(MyClass::class)``. The ``ClockMock::register`` method
296+
creates a mock of the time based functions into the same namespace as your class. So when using
297+
``time()`` you will use the mock instead of the default one::
298+
299+
namespace App;
300+
301+
class MyClass
302+
{
303+
public function getTimeInHours()
304+
{
305+
return time() / 3600;
306+
}
307+
}
308+
309+
.. code-block:: php
310+
311+
namespace App\Tests;
312+
313+
use App\MyClass;
314+
use PHPUnit\Framework\TestCase;
315+
316+
/**
317+
* @group time-sensitive
318+
*/
319+
class MyTest extends TestCase
320+
{
321+
public function testGetTimeInHours()
322+
{
323+
ClockMock::register(MyClass::class);
324+
325+
$my = new MyClass();
326+
327+
$result = $my->getTimeInHours();
328+
329+
$this->assertEquals(time() / 3600, $result);
330+
}
331+
}
332+
333+
.. caution::
334+
335+
Keep in mind that mocking is done by using the namespace resolutions rules
336+
(http://php.net/manual/en/language.namespaces.rules.php). So time-based functions need to be used as
337+
"Unqualified name", i.e. ``\time()`` cannot be mocked.
338+
291339
.. tip::
292340

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

0 commit comments

Comments
 (0)
0