控制台测试
在 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 仅用于必要的测试,有助于保持普通测试的执行速度。