経緯
・ Laravelにて、バッチ処理を書くにあたって、Commandで実装してgithub actionsで定期実行する形にしようと考えてバッチ処理実装
・ テスト書いてないとかお前それ t_wadaの前でも。。。があるので、テストももちろん書く!
・ マニュアルにあるように
https://readouble.com/laravel/8.x/ja/console-tests.html
$this->artisan('testBatch')
->expectsOutput('batch complete')
->assertExitCode(0);
と書く。
・ おーいけてるいけてる。じゃあDBの値の変更結果も確認しよう。
$this->artisan('testBatch')
->expectsOutput('batch complete')
->assertExitCode(0);
$this->assertEquals(Hoge::count(), 1);
FAILURES!
testBatchの中で1行レコードが追加されるはずなのに何で!?!?!?
結論
run()
で処理を明示的に実行させないとダメだった。
修正後
$this->artisan('testBatch')
->expectsOutput('batch complete')
->assertExitCode(0)
->run();
$this->assertEquals(Hoge::count(), 1);
run()
の記述が無い場合、プログラムの最後でrun()
が実行されるようで、command処理実行後の値を取得、アサーションする場合は明示的にrun()
を呼び出す必要があるみたい。
参考
・PendingCommandの__destruct()
でrun()
が実行される。
https://github.com/laravel/framework/blob/8.x/src/Illuminate/Testing/PendingCommand.php#L361
・execute()
はrun()
のエイリアス
https://github.com/laravel/framework/blob/8.x/src/Illuminate/Testing/PendingCommand.php#L200