Command line testing


Introduction

    Exception In addition to simplifying HTTP testing, Laravel provides a simple API for testing console applications that require user input.
  • Expected input/output
Laravel uses the
expectsQuestion

method to simulate the console command "User input. Additionally, you can specify the console command exit code and expected output text using the

assertExitCode

and

expectsOutput

methods. An example is as follows:

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.'.');
   });
You can refer to the following sample code to test the command, which uses the

expectsQuestion
,
expectsOutput

, and

assertExitCode

methods:

/**
 * 测试控制台命令。
 *
 * @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);
     }
This article was first published on the LearnKu.com website.