阅读(4829) (14)

Laravel 8 期望输入 / 输出

2021-07-08 16:54:53 更新

Laravel 使用 expectsQuestion 方法为控制台命令轻松地 “mock” 用户输入。此外,还可以使用 assertExitCodeexpectsOutput 方法指定控制台命令退出码和期望输出文本。可以参考下面的命令:

Artisan::command('question', function () {
    $name = $this->ask('What is your name?');

    $language = $this->choice('Which language do you program in?', [
        'PHP',
        'Ruby',
        'Python',
    ]);

    $this->line('Your name is '.$name.' and you program in '.$language.'.');
}); 

你可以参考下面的示例代码来测试此命令,该测试使用了 expectsQuestionexpectsOutput,和 assertExitCode 方法:

/**
 * 测试命令行
 *
 * @return void
 */
public function testConsoleCommand()
{
    $this->artisan('question')
         ->expectsQuestion('What is your name?', 'Taylor Otwell')
         ->expectsQuestion('Which language do you program in?', 'PHP')
         ->expectsOutput('Your name is Taylor Otwell and you program in PHP.')
         ->assertExitCode(0);
} 

当你写一个要确认的命令,“yes” 或者 “no” 时,你可以使用 expectsConfirmation 方法:

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