File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change @@ -232,6 +232,54 @@ test::
232232
233233And 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
You can’t perform that action at this time.
0 commit comments