> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# 控制台测试

> 学习如何在 Laravel 中测试 Artisan 命令（输入 / 输出期望值、退出码校验、控制台事件校验）。

# 控制台测试

在 Laravel 中，你可以简洁地为 Artisan 命令编写包含输入与输出的测试。

<Info>
  本页面基于 Laravel 最新的控制台测试 API，还涵盖了用于校验 Laravel Prompts 搜索输入的 `expectsSearch`。
</Info>

## 简介

使用 `artisan` 方法执行命令，并通过链式调用校验期望值。

<Tabs>
  <Tab title="Pest">
    ```php theme={null}
    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);
    });
    ```
  </Tab>

  <Tab title="PHPUnit">
    ```php theme={null}
    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);
    }
    ```
  </Tab>
</Tabs>

```mermaid theme={null}
flowchart TD
    A[通过 artisan 执行命令] --> B[定义输入期望值]
    B --> C[校验输出或表格]
    C --> D[校验退出状态]
```

## 成功 / 失败断言

通过校验退出状态可以判断命令的成功与失败。

```php theme={null}
$this->artisan('inspire')->assertExitCode(0);
$this->artisan('inspire')->assertSuccessful();
$this->artisan('inspire')->assertFailed();
```

## 输入 / 输出期望值

### 输入期望值

你可以模拟用户对问题输入和搜索输入的操作。

```php theme={null}
// 同时模拟问题输入和搜索输入
$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);
```

### 输出期望值

可以校验输出字符串的完全匹配、部分匹配以及表格显示。

```php theme={null}
// 确认仅显示期望的输出
$this->artisan('users:all')
    ->expectsOutput('The expected output')
    ->doesntExpectOutput('Unexpected output')
    ->expectsOutputToContain('expected')
    ->expectsTable([
        'ID',
        'Email',
    ], [
        [1, 'taylor@example.com'],
        [2, 'abigail@example.com'],
    ])
    ->assertExitCode(0);
```

## 确认期望值

对于 Yes / No 的确认提示，使用 `expectsConfirmation`。

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

## 控制台事件

默认情况下，测试执行时不会触发 `CommandStarting` / `CommandFinished`。

需要校验事件的测试类可以添加 `WithConsoleEvents`。

```php theme={null}
<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\WithConsoleEvents;
use Tests\TestCase;

class ConsoleEventTest extends TestCase
{
    use WithConsoleEvents;
}
```

<Tip>
  将 `WithConsoleEvents` 仅用于必要的测试，有助于保持普通测试的执行速度。
</Tip>


## Related topics

- [Artisan 控制台](/zh/artisan.md)
- [浏览器测试（Dusk）](/zh/dusk.md)
- [Laravel Prompts](/zh/prompts.md)
- [进程](/zh/processes.md)
- [教程 - Laravel Console Starter](/zh/packages/laravel-console-starter/tutorial.md)
