LoginSignup
3
0

More than 1 year has passed since last update.

LaravelでArtisanコマンド(コマンドライン(Command))処理のテストを書く

Last updated at Posted at 2021-08-02

経緯

・ 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

3
0
1

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
3
0