File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed
user_guide_src/source/testing Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff 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
272289Testing CLI Output
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments