Laravel Console 测试

简介

除了简化 HTTP 测试外,Laravel 还为测试需要用户输入的控制台应用提供了简单的 API。


期望输入/输出

Laravel 允许我们使用 expectsQuestion 方法为控制台命令轻松“模拟”用户输入,此外,我们还可以使用 assertExitCodeexpectsOutput 方法指定控制台命令退出码和期望输出的文本。例如,考虑下面这个控制台命令(定义在 routes/console.php 中):

Artisan::command('question', function () {
    $name = $this->ask('What is your name?');
    $language = $this->choice('Which language do you program in?', [
        'PHP',
        'Golang',
        'Python',
    ]);
    $this->line('Your name is '.$name.' and you program in '.$language.'.');
});

我们可以为 question 命令编写测试代码如下,其中使用到了 expectsQuestionexpectsOutputassertExitCode 方法:

/**
 * Test a console command.
 *
 * @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);

查看笔记

扫码一下
查看教程更方便