如何为Laravel的scheduled commands定时命令编写单元测试
Laravel 调度任务单元测试实现
以下是针对你给出的abc:some-function调度任务的两种常用测试方案,可根据需求选择或搭配使用:
方案1:直接校验调度配置(轻量快速)
直接读取调度器注册的事件,校验任务的 Cron 表达式、参数、运行配置是否符合预期,适合快速验证配置正确性。
<?php namespace Tests\Feature; use Illuminate\Console\Scheduling\Schedule; use Tests\TestCase; class ScheduleTest extends TestCase { public function test_abc_some_function_schedule_config() { $schedule = $this->app->make(Schedule::class); // 筛选目标命令对应的调度事件 $targetEvent = collect($schedule->events()) ->first(fn($event) => str_contains($event->command, 'abc:some-function')); // 断言任务已注册 $this->assertNotNull($targetEvent); // 断言调度规则为每月10号9点,对应Cron表达式为 0 9 10 * * $this->assertEquals('0 9 10 * *', $targetEvent->expression); // 断言命令传入的参数符合预期,把{your-argument}替换成你实际传入的参数值 $this->assertStringContainsString('{your-argument}', $targetEvent->command); } }
方案2:模拟时间触发验证(贴近真实运行场景)
通过冻结系统时间,执行调度运行命令,验证对应时间点任务是否会被正确触发,适合做端到端的调度逻辑验证。
<?php namespace Tests\Feature; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Carbon; use Tests\TestCase; class ScheduleRunTest extends TestCase { public function test_abc_some_function_triggers_at_correct_time() { Artisan::fake(); // 验证非触发时间不会执行 Carbon::setTestNow('2024-06-10 08:59:00'); $this->artisan('schedule:run'); Artisan::assertNotRan('abc:some-function', [ 'argument' => '{your-argument}' // 替换为实际参数值 ]); // 验证触发时间会正常执行 Carbon::setTestNow('2024-06-10 09:00:00'); $this->artisan('schedule:run'); Artisan::assertRan('abc:some-function', [ 'argument' => '{your-argument}' // 替换为实际参数值 ]); } }
注意事项
- 代码中的
{your-argument}需要替换为你实际给命令传入的参数值,和你注册调度时填写的参数保持一致即可 - 如果你的任务配置了队列运行、环境限制等规则,也可以对应补充断言,比如
$this->assertTrue($targetEvent->runsInQueue)验证队列配置 - 两种方案可以同时使用,方案1做配置校验,方案2做触发逻辑校验,覆盖度更高
内容的提问来源于stack exchange,提问作者davisria
相关产品推荐
相关产品推荐

