raigu/psr20-clock-testdoubles

PSR-20 时钟接口的测试双

dev-main / 0.1.x-dev 2021-09-02 18:26 UTC

This package is auto-updated.

Last update: 2024-08-29 05:56:00 UTC


README

Latest Stable Version Latest Unstable Version Fallows SemVer build codecov Mutation testing badge License: MIT

PSR-20 时钟的测试双

不稳定,因为 PSR-20 尚未正式发布。

兼容性

  • PHP 7.4, ^8.0
  • psr/clock==@dev

变更

./CHANGELOG.md

安装

$ composer require --dev raigu/psr20-clock-testdoubles

测试双

FrozenClock

时间冻结的时钟。无论调用多少次 now,它总是返回相同的时间。

// creating with current system date and time
$clock = new \Raigu\TestDouble\Psr20\FrozenClock;

// creating with predefined date and time at
$clock = new \Raigu\TestDouble\Psr20\FrozenClock(
    new DateTimeImmutable('2020-01-02')
);

TimeTravelClock

像正常时钟一样运行的时钟,但如果给定时间,会有时间偏移。

// By default, acts like normal clock. 
$clock = new \Raigu\TestDouble\Psr20\TimeTravelClock();
$moment = $clock->now();
sleep(2);
// after two seconds the TimeTravelClock is also moved forward.
assert($moment->add(new DateInterval('PT2S'))->getTimestamp() === $clock->now()->getTimestamp());

// Moving to the specific date and time in the future or past:
$clock->travelInTime(new DateTimeImmutable('2020-01-02'));
assert($clock->now()->format('Y-m-d') === '2020-01-02');

// Move by the specific interval to the future
$clock->travelInTimeByInterval(new DateInterval('P10D'));
assert($clock->now()->format('Y-m-d') === '2020-01-12');

// Move by the specific interval to the past
$clock->travelInTimeByInterval(DateInterval::createFromDateString('-1 day'));
assert($clock->now()->format('Y-m-d') === '2020-01-11');

TimeTravelClock 通过包装时钟实现来实现装饰器模式。默认情况下,它使用系统时钟实现,但可以在构造函数中替换。

例如,可以使用 FrozenClock 创建一个冻结的 TimeTravelClock

$clock = new \Raigu\TestDouble\Psr20\TimeTravelClock(
    new Raigu\TestDouble\Psr20\FrozenClock()
);
$moment = $clock->now();
sleep(2);
assert($moment->getTimestamp() === $clock->getTimestamp(), 'Does not tick because base clock is frozen.');

测试

$ composer test
$ composer specification 
$ composer coverage