0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravelで非同期のJobをテストする3つ方法(同期処理にして確認する)

Posted at

結論

  • Laravelで非同期の処理を同期実行してテストしたい場合はconfig(['queue.default' => 'sync'])するのがいい

1. dispatchSyncメソッドでジョブを実行する

DeleteUserJob::dispatchSync($userId);

✅ pros: 簡単に実装でき、特定のジョブを確実に実行できる
❌ cons: ジョブに依存したテストになる

2. Artisan::call('queue:work --once')でジョブを実行する

Artisan::call('queue:work --once');

✅ pros: 実際のキューワーカーの動作に近い
❌ cons: テストの実行速度が遅くなる

3. config(['queue.default' => 'sync'])でジョブを同期実行する

config(['queue.default' => 'sync']);

✅ pros: キューを同期的に実行でき、テストが簡潔になる
❌ cons: 非同期処理の一部の側面(遅延、再試行など)をテストできない

実装例

phpCopypublic function testDeleteUser()
{
    // キューの実行をsyncに設定
    config(['queue.default' => 'sync']);

    $user = User::factory()->create();
    $response = $this->deleteJson("/api/users/{$user->id}");

    $response->assertStatus(200);
    $this->assertDatabaseMissing('users', ['id' => $user->id]);
}

🚨 注意点

実際の非同期処理をシミュレートしていないため、遅延ジョブや再試行ロジックなどの特定の機能はテストできない
本番環境との動作の違いに注意が必要

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?