Laravel: Test Console
Cùng với test HTTP thì Laravel cung cấp một API đơn giản cho việc test console applications yêu cầu input từ người dùng.
Mong muốn Input / Output
Laravel cho phép ta dễ dàng "giả định" input người dùng với các lệnh console sử dụng phương thức expectsQuestion
. Cùng với đó thì ta có thể chỉ định exit code và text mà ta mong muốn được output bởi console command sử dụng các phương thức assertExitCode
và expectsOutput
. Ví dụ ta xét console command sau đây:
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.'.');
});
Ta có thể test lệnh này bằng đoạn test sau đây sử dụng các phương thức expectsQuestion
, expectsOutput
, và assertExitCode
:
/**
* Test a console command.
*
* @return void
*/
public function test_console_command()
{
$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);
}