Skip to content

Commit

Permalink
docs: add missing Time::setTestNow()
Browse files Browse the repository at this point in the history
  • Loading branch information
kenjis committed Nov 25, 2023
1 parent 1d6b7ac commit 63f42ba
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
17 changes: 17 additions & 0 deletions user_guide_src/source/testing/overview.rst
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,23 @@ component name:

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

Testing and Time
================

Testing time-dependent code can be challenging. However, when using the
:doc:`Time <../libraries/time>` class, the current time can be fixed or changed
at will during testing.

Below is a sample test code that fixes the current time:

.. literalinclude:: overview/021.php

You can fix the current time with the ``Time::setTestNow()`` method.
Optionally, you can specify a locale as the second parameter.

Don't forget to reset the current time after the test with calling it without
parameters.

.. _testing-cli-output:

Testing CLI Output
Expand Down
24 changes: 24 additions & 0 deletions user_guide_src/source/testing/overview/021.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

use CodeIgniter\I18n\Time;
use CodeIgniter\Test\CIUnitTestCase;

final class TimeDependentCodeTest extends CIUnitTestCase
{
protected function tearDown(): void
{
parent::tearDown();

// Reset the current time.
Time::setTestNow();
}

public function testFixTime(): void
{
// Fix the current time to "2023-11-25 12:00:00".
Time::setTestNow('2023-11-25 12:00:00');

// This assertion always passes.
$this->assertSame('2023-11-25 12:00:00', (string) Time::now());
}
}

0 comments on commit 63f42ba

Please sign in to comment.