#はじめに
HTTPテストを簡単にするだけでなく、LaravelはアプリケーションのカスタムコンソールコマンドをテストするためのシンプルなAPIも提供します。
#成功 / 失敗の期待値
まずは、Artisanコマンドの終了コードに関するアサーションの方法を見ていきましょう。これには、テスト内でArtisanコマンドを呼び出すためにartisanメソッドを使います。その後、assertExitCodeメソッドで指定した終了コードでコマンドが完了したことをアサートします。
/**
* コンソールコマンドのテスト。
*/
public function test_console_command(): void
{
$this->artisan('inspire')->assertExitCode(0);
}
assertNotExitCodeメソッドを使うと、指定した終了コードで終了しなかったことをアサートできます。
$this->artisan('inspire')->assertNotExitCode(1);
もちろん、ほとんどのターミナルコマンドは成功時に0のステータスコードで終了し、失敗時には0以外のコードで終了します。便利なため、assertSuccessfulとassertFailedアサーションを使って、コマンドが成功終了したかどうかを簡単に確認できます。
$this->artisan('inspire')->assertSuccessful();
$this->artisan('inspire')->assertFailed();
#入力 / 出力の期待値
Laravelでは、expectsQuestionメソッドを使ってコンソールコマンドのユーザー入力を簡単にモックできます。さらに、assertExitCodeやexpectsOutputメソッドでコマンドの終了コードや出力テキストの期待値を指定できます。例えば、以下のコンソールコマンドを考えてみましょう。
Artisan::command('question', function () {
$name = $this->ask('What is your name?');
$language = $this->choice('Which language do you prefer?', [
'PHP',
'Ruby',
'Python',
]);
$this->line('Your name is '.$name.' and you prefer '.$language.'.');
});
このコマンドは、以下のテストでexpectsQuestion、expectsOutput、doesntExpectOutput、expectsOutputToContain、doesntExpectOutputToContain、assertExitCodeメソッドを使ってテストできます。
/**
* Test a console command.
*/
public function test_console_command(): void
{
$this->artisan('question')
->expectsQuestion('What is your name?', 'Taylor Otwell')
->expectsQuestion('Which language do you prefer?', 'PHP')
->expectsOutput('Your name is Taylor Otwell and you prefer PHP.')
->doesntExpectOutput('Your name is Taylor Otwell and you prefer Ruby.')
->expectsOutputToContain('Taylor Otwell')
->doesntExpectOutputToContain('you prefer Ruby')
->assertExitCode(0);
}
#確認の期待値
「はい」か「いいえ」の回答を期待するコマンドを書く場合は、expectsConfirmationメソッドを使えます。
$this->artisan('module:import')
->expectsConfirmation('Do you really wish to run this command?', 'no')
->assertExitCode(1);
#テーブルの期待値
Artisanのtableメソッドで情報のテーブルを表示するコマンドの場合、テーブル全体の出力期待値を書くのは面倒です。代わりにexpectsTableメソッドを使えます。このメソッドは最初の引数にテーブルのヘッダー、2番目の引数にテーブルのデータを受け取ります。
$this->artisan('users:all')
->expectsTable([
'ID',
'Email',
], [
[1, '[email protected]'],
[2, '[email protected]'],
]);
#コンソールイベント
デフォルトでは、Illuminate\Console\Events\CommandStartingとIlluminate\Console\Events\CommandFinishedイベントはアプリケーションのテスト実行中には発火しません。ただし、テストクラスにIlluminate\Foundation\Testing\WithConsoleEventsトレイトを追加すると、これらのイベントを有効にできます。
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\WithConsoleEvents;
use Tests\TestCase;
class ConsoleEventTest extends TestCase
{
use WithConsoleEvents;
// ...
}