Laravel:测试命令时无法获得工作通知::assertSentTo

问题描述 投票:0回答:1

Laravel 9

我的 Laravel 应用程序确实有先前的测试来验证发送的通知。典型的

Notification::fake();

$this->post('/forgot-password', ['email' => $user->email]);

Notification::assertSentTo($user, ResetPassword::class);

还有一些类似的其他。但是...现在我正在测试从命令调用发送的通知,事情发生了不同。

public function testHandle_happyPath()
{
    Notification::fake();

    $customer = CustomerFactory::new()->default()->create([
        'account_status' => AccountStatus::TRIAL,
        'created_at' => Carbon::now()->subDays(28)
    ]);
    ConfigurationKey::PREVIOUS_DAYS_TO_NOTIFY_TRIAL_EXPIRY()->setInteger(2);

    $result = $this->artisan(NotifyTrialsToExpireCommand::class);

    $customer->refresh();
    $result->assertSuccessful();
    Notification::assertSentTo($customer, TrialNextToExpireNotification::class);
}

结果是

未发送预期的 [App\Notifications\TrialNextToExpireNotification] 通知。

我的 phpunit conf 已经有

<server name="QUEUE_CONNECTION" value="sync"/>
以避免任何相关问题。

我已经手动测试过,它可以工作。

很明显,它与

$this->artisan
调用的使用直接相关。有什么事情是我可以忽略的?这种类型的测试应该以不同的方式准备吗?我这样测试不行吗?

php laravel phpunit
1个回答
0
投票

尝试以这种方式运行它,看看会发生什么。而不是

$result = $this->artisan(NotifyTrialsToExpireCommand::class);

$customer->refresh();
$result->assertSuccessful();

运行:

$this->artisan(NotifyTrialsToExpireCommand::class)
    ->assertSuccessful();

$customer->refresh();

是的,像这样更改顺序(使用变量)会影响它的运行时间。

根据

$this->artisan(...)
的工作方式,它将使用
__destruct
神奇的 PHP 关键字来执行命令,并且由于您使用
$result = 
然后调用断言,它可能无法正确触发(如预期)。

© www.soinside.com 2019 - 2024. All rights reserved.