扫码一下
查看教程更方便
除了简化 http 测试外,laravel 还为测试需要用户输入的控制台应用提供了简单的 api。
laravel 允许我们使用 expectsquestion
方法为控制台命令轻松“模拟”用户输入,此外,我们还可以使用 assertexitcode
和 expectsoutput
方法指定控制台命令退出码和期望输出的文本。例如,考虑下面这个控制台命令(定义在 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 命令编写测试代码如下,其中使用到了 expectsquestion
、expectsoutput
和 assertexitcode
方法:
/**
* 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);