@@ -147,3 +147,61 @@ being in a month or another.
147
147
.. versionadded :: 6.3
148
148
149
149
The :class: `Symfony\\ Component\\ Clock\\ ClockAwareTrait ` was introduced in Symfony 6.3.
150
+
151
+ Writing Time-Sensitive Tests
152
+ ----------------------------
153
+
154
+ The Clock component provides another trait, this one easing you the writing of time-sensitive
155
+ tests: the :class: `Symfony\\ Component\\ Clock\\ Test\\ ClockSensitiveTrait `. The purpose
156
+ of this trait is to provide methods to freeze time and restore the global clock after
157
+ each test.
158
+
159
+ To interact with the mocked clock in your tests, you will have to use the ``ClockSensitiveTrait::mockTime() ``
160
+ method. This method accepts many types as its only argument:
161
+
162
+ * A string, which can be a date or an interval. Examples: ``1996-07-01 `` or ``+2 days ``
163
+ * A ``DateTimeImmutable `` to set the clock at
164
+ * A boolean, to freeze or restore the global clock
165
+
166
+ Let's say you want to test the method ``MonthSensitive::isWinterMonth() `` of the above example.
167
+ An approach of the test class could be written this way::
168
+
169
+ namespace App\Tests\TimeUtils;
170
+
171
+ use App\TimeUtils\MonthSensitive;
172
+ use PHPUnit\Framework\TestCase;
173
+ use Symfony\Component\Clock\Test\ClockSensitiveTrait;
174
+
175
+ class MonthSensitiveTest extends TestCase
176
+ {
177
+ use ClockSensitiveTrait;
178
+
179
+ public function testIsWinterMonth(): void
180
+ {
181
+ $clock = static::mockTime(new \DateTimeImmutable('2022-03-02'));
182
+
183
+ $monthSensitive = new MonthSensitive();
184
+ $monthSensitive->setClock($clock);
185
+
186
+ $this->assertTrue($monthSensitive->isWinterMonth());
187
+ }
188
+
189
+ public function testIsNotWinterMonth(): void
190
+ {
191
+ $clock = static::mockTime(new \DateTimeImmutable('2023-06-02'));
192
+
193
+ $monthSensitive = new MonthSensitive();
194
+ $monthSensitive->setClock($clock);
195
+
196
+ $this->assertFalse($monthSensitive->isWinterMonth());
197
+ }
198
+ }
199
+
200
+ It doesn't matter which time of the year you are running this test, it will always behave
201
+ the same way. By combining the :class: `Symfony\\ Component\\ Clock\\ ClockAwareTrait ` and
202
+ :class: `Symfony\\ Component\\ Clock\\ Test\\ ClockSensitiveTrait `, you have full control on
203
+ your time-sensitive code's behavior.
204
+
205
+ .. versionadded :: 6.3
206
+
207
+ The :class: `Symfony\\ Component\\ Clock\\ Test\\ ClockSensitiveTrait ` was introduced in Symfony 6.3.
0 commit comments