如何对日期相关的 Symfony 命令进行 Behat 测试?

How to Behat test for date dependent Symfony command?

我 运行 一个适用于上个月交易的 CLI Symfony 命令。这是 CLI——我不能只模拟系统时钟,那么我该如何用 Behat 测试它呢?现在是 11 月,以下情况将在 12 月失败:

  Scenario: Do something with last month transactions
    Given there is a transaction "7ccf7387" for 2020-10
    And there is a transaction "39d7f278" for 2020-10
    When I execute "bin/console billing:last-month" from project root
    Then command should succeed
    And output should contain "Closed 2 transactions"

这是当前的命令实现:

    final class CloseLastMonth extends Command
    {
        /* ... */
    
        protected function execute(InputInterface $input, OutputInterface $output): int
        {
            $month = (GregorianCalendar::UTC())->currentMonth()->previous();
            $trxs = $this->bus->dispatch(new GetActiveTrxsByMonthQuery($month));
            foreach ($trxs as $trx) {
                $this->bus->dispatch(new CloseTransactionCommand($trx->id));
            }
            $this->io->success(sprintf('Closed %d transactions', count($trxs)));
    
            return 0;
        }
    
        /* ... */
    }

我可以强制用户始终在命令参数中传递当前月份,但这并不优雅。始终 returns 当前月份的新 Symfony 服务有点矫枉过正。

更好write your own step definition:

/**
 * @Given /^There is a transaction "([^"]*)" for last month$/
 */
public function thereIsATransaction(string $transactionId) {}

这样你就可以简单地做到:

Given there is a transaction "7ccf7387" for last month
    And there is a transaction "39d7f278" for last month