콘솔 테스트
Laravel에서는 Artisan 명령에 대해 입력·출력을 포함한 테스트를 간결하게 작성할 수 있습니다.
이 페이지는 Laravel 최신 콘솔 테스트 API에 맞춰져 있으며, Laravel Prompts의 검색 입력을 검증하는 expectsSearch도 다룹니다.
artisan 메서드로 명령을 실행하고 기대값을 체이닝하여 검증합니다.
test('question 명령', function () {
// 사용자 입력과 출력을 순서대로 검증한다
$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.')
->assertExitCode(0);
});
public function test_question_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.')
->assertExitCode(0);
}
성공 / 실패 어서션
종료 상태를 검증하여 명령의 성공·실패를 판정할 수 있습니다.
$this->artisan('inspire')->assertExitCode(0);
$this->artisan('inspire')->assertSuccessful();
$this->artisan('inspire')->assertFailed();
입력 / 출력 기대값
입력 기대값
질문 입력이나 검색 입력에 대한 사용자 조작을 모의할 수 있습니다.
// 질문 입력과 검색 입력을 모두 모의한다
$this->artisan('example')
->expectsQuestion('What is your name?', 'Taylor Otwell')
->expectsSearch('What is your name?', search: 'Tay', answers: [
'Taylor Otwell',
'Taylor Swift',
'Darian Taylor',
], answer: 'Taylor Otwell')
->assertExitCode(0);
출력 기대값
출력 문자열의 완전 일치·부분 일치·테이블 표시를 검증할 수 있습니다.
// 기대하는 출력만 표시되는지 확인한다
$this->artisan('users:all')
->expectsOutput('The expected output')
->doesntExpectOutput('Unexpected output')
->expectsOutputToContain('expected')
->expectsTable([
'ID',
'Email',
], [
[1, '[email protected]'],
[2, '[email protected]'],
])
->assertExitCode(0);
확인 프롬프트 기대값
Yes / No 확인 프롬프트에는 expectsConfirmation을 사용합니다.
$this->artisan('module:import')
->expectsConfirmation('Do you really wish to run this command?', 'no')
->assertExitCode(1);
콘솔 이벤트
기본적으로 테스트 실행 시에는 CommandStarting / CommandFinished가 발생하지 않습니다.
이벤트 검증이 필요한 테스트 클래스에는 WithConsoleEvents를 추가합니다.
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\WithConsoleEvents;
use Tests\TestCase;
class ConsoleEventTest extends TestCase
{
use WithConsoleEvents;
}
WithConsoleEvents는 필요한 테스트에 한정해서 사용하면 일반 테스트 속도를 유지하기 쉬워집니다.