Skip to content

Console Tests

Nguồn gốc: Bản dịch từ Console Tests

Giới thiệu (Introduction)

Ngoài HTTP testing, Laravel cung cấp API đơn giản để test custom console commands.

Success / Failure Expectations

Dùng method artisan để gọi command, kết hợp assertExitCode để kiểm tra exit code:

php
test('console command', function () {
    $this->artisan('inspire')->assertExitCode(0);
});
php
public function test_console_command(): void
{
    $this->artisan('inspire')->assertExitCode(0);
}

Kiểm tra không phải exit code cụ thể:

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

Shortcut tiện lợi:

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

Input / Output Expectations

"Mock" user input với expectsQuestion và kiểm tra output:

php
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.'.');
});

Test:

php
test('console command', 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);
});
php
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.')
        ->assertExitCode(0);
}

Confirmation Expectations

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

Table Expectations

Kiểm tra output dạng bảng với expectsTable.

Console Events

Mặc định Illuminate\Console\Events\CommandStartingCommandFinished không dispatch khi test. Bật:

php
$this->withConsoleEvents();