shopery/datetime

DateTime 辅助工具,简化测试过程

0.2 2017-05-26 06:48 UTC

This package is not auto-updated.

Last update: 2024-09-23 06:28:19 UTC


README

⚠ 注意 ⚠

此库尚未准备好用于生产,可能会经历重大变更。

简单的 DateTime 提供者。允许在测试时冻结时间。

安装

您可以安装此库

  • 使用 composer 安装: composer require shopery/datetime
  • 使用 官方 Git 仓库git clone https://github.com/shopery/datetime.

用法

将每个 new DateTime() 替换为对 Shopery\DateTime\DateTime::now() 的调用,以提高可测试性。

要创建相对日期时间,无论是过去还是未来,请使用 Shopery\DateTime\DateTime::create($timeString) 并传递一个 GNU 字符串修饰符

冻结时间

您可以使用静态方法 DateTime::freeze() 冻结时间。传递任何日期作为参数以设置当前冻结时间。这允许测试依赖于时间的场景。您应该在测试结束时调用 DateTime::unfreeze 以清除它。

示例

use Shopery\DateTime\DateTime;
use DateTime as NativeDateTime;

class Coupon
{
    private $expiredTime;

    public function __construct(NativeDateTime $expiredTime)
    {
        $this->expiredTime = $expiredTime;
    }

    public function hasExpired()
    {
        return DateTime::now() > $this->expiredTime;
    }
}

class CouponTest
{
    public function test_has_expired()
    {
        $coupon = new Coupon(DateTime::create('yesterday'));

        $this->assertTrue($coupon->hasExpired());

        $frozenTime = DateTime::create('a month ago');
        DateTime::freeze($frozenTime);

        $this->assertFalse($coupon->hasExpired());

        DateTime::unfreeze();
    }
}

PHPUnit 监听器

您可以将 PHPUnit 配置为在运行一些测试时冻结时间。提供了一个 PHPUnit 监听器,为您的测试添加了 freezeTime 注解。以下是您需要在您的 phpunit.xml 中进行的更改

<phpunit>
    ...
    <listeners>
        <listener class="Shopery\DateTime\Listener\PHPUnit\DateTimeListener" />
    </listeners>
    ...
</phpunit>

现在,您可以在每个测试的 PHPDoc 中添加 @freezeTime

class MyTest
{
    /**
     * @freezeTime
     */
    public function test_frozen_in_current_time()
    {
    }

    /**
     * @freezeTime 2015-01-31 08:30:00
     */
    public function test_frozen_in_a_given_date()
    {
    }

    /**
     * @freezeTime first monday of January last year
     */
    public function test_frozen_in_a_relative_date()
    {
    }

    public function test_this_is_not_frozen()
    {
    }
}