Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add missing Time::setTestNow() #8251

Merged
merged 1 commit into from
Nov 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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());
}
}