gau*_*mar 2 testing phpunit laravel laravel-jobs laravel-9
在 Laravel 中进行基于 phpUnit 的单元测试时,我发现了两种测试作业是否被调度的方法 -
1.
$this->expectsJobs(JobClassName::class);
2.
Bus::fake();
Bus::assertDispatched(JobClassName::class);
Run Code Online (Sandbox Code Playgroud)
在仔细检查 Laravel 文档后,我无法弄清楚上述哪一种方法是更好的方法以及这两种方法之间的功能差异是什么。
如果您正确阅读了文档,您将看到可以使用:
public function test_orders_can_be_shipped()
{
Queue::fake();
// Perform order shipping...
// Assert that no jobs were pushed...
Queue::assertNothingPushed();
// Assert a job was pushed to a given queue...
Queue::assertPushedOn('queue-name', ShipOrder::class);
// Assert a job was pushed twice...
Queue::assertPushed(ShipOrder::class, 2);
// Assert a job was not pushed...
Queue::assertNotPushed(AnotherJob::class);
}
Run Code Online (Sandbox Code Playgroud)
因此,请务必使用Queue::fake();,并在运行代码后使用:
Queue::assertPushed(YourJob::class, 1);
// Or
Queue::assertPushed(function (YourJob $job) use ($variable) {
return $job->property === $variable;
});
Run Code Online (Sandbox Code Playgroud)