Skip to content

Commit 522fe98

Browse files
committed
[Clock] Fix calling mockTime() in setUpBeforeClass()
1 parent 3a0bd83 commit 522fe98

File tree

2 files changed

+67
-1
lines changed

2 files changed

+67
-1
lines changed

src/Symfony/Component/Clock/Test/ClockSensitiveTrait.php

+7-1
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,20 @@ public static function mockTime(string|\DateTimeImmutable|bool $when = true): Cl
4242
}
4343

4444
/**
45+
* @beforeClass
46+
*
4547
* @before
4648
*
4749
* @internal
4850
*/
49-
protected static function saveClockBeforeTest(bool $save = true): ClockInterface
51+
public static function saveClockBeforeTest(bool $save = true): ClockInterface
5052
{
5153
static $originalClock;
5254

55+
if ($save && $originalClock) {
56+
self::restoreClockAfterTest();
57+
}
58+
5359
return $save ? $originalClock = Clock::get() : $originalClock;
5460
}
5561

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Clock\Tests;
13+
14+
use PHPUnit\Framework\TestCase;
15+
use Psr\Clock\ClockInterface;
16+
use Symfony\Component\Clock\Clock;
17+
use Symfony\Component\Clock\MockClock;
18+
use Symfony\Component\Clock\NativeClock;
19+
use Symfony\Component\Clock\Test\ClockSensitiveTrait;
20+
21+
class ClockBeforeClassTest extends TestCase
22+
{
23+
use ClockSensitiveTrait;
24+
25+
private static ?ClockInterface $clock = null;
26+
27+
public static function setUpBeforeClass(): void
28+
{
29+
self::$clock = self::mockTime();
30+
}
31+
32+
public static function tearDownAfterClass(): void
33+
{
34+
self::$clock = null;
35+
}
36+
37+
public function testMockClock()
38+
{
39+
$this->assertInstanceOf(MockClock::class, self::$clock);
40+
$this->assertInstanceOf(NativeClock::class, Clock::get());
41+
42+
$clock = self::mockTime();
43+
$this->assertInstanceOf(MockClock::class, Clock::get());
44+
$this->assertSame(Clock::get(), $clock);
45+
46+
$this->assertNotSame($clock, self::$clock);
47+
48+
self::restoreClockAfterTest();
49+
self::saveClockBeforeTest();
50+
51+
$this->assertInstanceOf(MockClock::class, self::$clock);
52+
$this->assertInstanceOf(NativeClock::class, Clock::get());
53+
54+
$clock = self::mockTime();
55+
$this->assertInstanceOf(MockClock::class, Clock::get());
56+
$this->assertSame(Clock::get(), $clock);
57+
58+
$this->assertNotSame($clock, self::$clock);
59+
}
60+
}

0 commit comments

Comments
 (0)