본문 바로가기

콘솔 테스트

번역일: 2026년 6월 20일

콘솔 테스트

소개

Laravel은 HTTP 테스트를 간편하게 지원하는 것처럼, 커스텀 Artisan 명령어 테스트를 위한 간결한 API도 제공합니다.

성공 / 실패 검증

먼저 Artisan 명령어의 종료 코드(exit code)를 검증하는 방법을 살펴보겠습니다. 테스트에서 artisan 메서드로 명령어를 실행한 뒤, assertExitCode 메서드로 원하는 종료 코드와 일치하는지 확인할 수 있습니다.

/** * 콘솔 명령어 테스트 */ public function test_console_command(): void { $this->artisan('inspire')->assertExitCode(0); }

반대로 특정 종료 코드로 종료되지 않았음을 검증하려면 assertNotExitCode 메서드를 사용합니다.

$this->artisan('inspire')->assertNotExitCode(1);

일반적으로 터미널 명령어는 성공 시 0, 실패 시 0이 아닌 값을 반환합니다. 이런 관례에 맞게 assertSuccessfulassertFailed를 사용하면 종료 코드를 직접 지정하지 않아도 성공/실패 여부를 간편하게 검증할 수 있습니다.

$this->artisan('inspire')->assertSuccessful(); $this->artisan('inspire')->assertFailed();

입력 / 출력 검증

Laravel은 expectsQuestion 메서드를 통해 콘솔 명령어의 사용자 입력을 손쉽게 모킹(mock)할 수 있습니다. 또한 expectsOutput으로 출력 텍스트를, assertExitCode로 종료 코드를 검증할 수 있습니다.

예를 들어 다음과 같은 콘솔 명령어가 있다고 가정해봅시다.

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 메서드를 조합하여 사용합니다.

/** * 콘솔 명령어 테스트 */ 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); }

확인(Confirmation) 검증

"yes" 또는 "no" 형태의 확인 응답이 필요한 명령어를 테스트할 때는 expectsConfirmation 메서드를 사용합니다.

$this->artisan('module:import') ->expectsConfirmation('Do you really wish to run this command?', 'no') ->assertExitCode(1);

테이블 출력 검증

명령어가 Artisan의 table 메서드로 테이블을 출력하는 경우, 전체 출력 문자열을 직접 비교하기 번거로울 수 있습니다. 이럴 때는 expectsTable 메서드를 사용하세요. 첫 번째 인자로 헤더 배열을, 두 번째 인자로 데이터 배열을 전달합니다.

$this->artisan('users:all') ->expectsTable([ 'ID', 'Email', ], [ [1, 'taylor@example.com'], [2, 'abigail@example.com'], ]);

콘솔 이벤트

기본적으로 테스트 실행 중에는 Illuminate\Console\Events\CommandStartingIlluminate\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; // ... }

NOTE

콘솔 이벤트는 명령어 실행 전후에 특정 로직을 연결할 때 유용합니다. 단, 대부분의 테스트에서는 이벤트가 필요하지 않으므로 기본적으로 비활성화 상태로 유지됩니다.

이 문서는 Laravel 공식 문서(MIT)를 한국 개발자를 위해 번역·재구성한 것입니다.

번역일: 2026년 6월 20일