Skip to content

Commit 645e93c

Browse files
authored
Merge pull request #8251 from kenjis/docs-testing-and-time
docs: add missing Time::setTestNow()
2 parents b835455 + fb03483 commit 645e93c

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

user_guide_src/source/testing/overview.rst

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,23 @@ component name:
267267

268268
.. note:: All component Factories are reset by default between each test. Modify your test case's ``$setUpMethods`` if you need instances to persist.
269269

270+
Testing and Time
271+
================
272+
273+
Testing time-dependent code can be challenging. However, when using the
274+
:doc:`Time <../libraries/time>` class, the current time can be fixed or changed
275+
at will during testing.
276+
277+
Below is a sample test code that fixes the current time:
278+
279+
.. literalinclude:: overview/021.php
280+
281+
You can fix the current time with the ``Time::setTestNow()`` method.
282+
Optionally, you can specify a locale as the second parameter.
283+
284+
Don't forget to reset the current time after the test with calling it without
285+
parameters.
286+
270287
.. _testing-cli-output:
271288

272289
Testing CLI Output
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
use CodeIgniter\I18n\Time;
4+
use CodeIgniter\Test\CIUnitTestCase;
5+
6+
final class TimeDependentCodeTest extends CIUnitTestCase
7+
{
8+
protected function tearDown(): void
9+
{
10+
parent::tearDown();
11+
12+
// Reset the current time.
13+
Time::setTestNow();
14+
}
15+
16+
public function testFixTime(): void
17+
{
18+
// Fix the current time to "2023-11-25 12:00:00".
19+
Time::setTestNow('2023-11-25 12:00:00');
20+
21+
// This assertion always passes.
22+
$this->assertSame('2023-11-25 12:00:00', (string) Time::now());
23+
}
24+
}

0 commit comments

Comments
 (0)