Console Tests

Introduction

In addition to simplifying HTTP testing, Laravel provides a simple API for testing console applications that ask for user input.

Expecting Input / Output

Laravel allows you to easily “mock” user input for your console commands using the expectsQuestion method. In addition, you may specify the exit code and text that you expect to be output by the console command using the assertExitCode and expectsOutput methods. For example, consider the following console command:

  1. Artisan::command('question', function () {
  2. $name = $this->ask('What is your name?');
  3. $language = $this->choice('Which language do you program in?', [
  4. 'PHP',
  5. 'Ruby',
  6. 'Python',
  7. ]);
  8. $this->line('Your name is '.$name.' and you program in '.$language.'.');
  9. });

You may test this command with the following test which utilizes the expectsQuestion, expectsOutput, and assertExitCode methods:

  1. /**
  2. * Test a console command.
  3. *
  4. * @return void
  5. */
  6. public function testConsoleCommand()
  7. {
  8. $this->artisan('question')
  9. ->expectsQuestion('What is your name?', 'Taylor Otwell')
  10. ->expectsQuestion('Which language do you program in?', 'PHP')
  11. ->expectsOutput('Your name is Taylor Otwell and you program in PHP.')
  12. ->assertExitCode(0);
  13. }

When writing a command which expects a confirmation in the form of a “yes” or “no” answer, you may utilize the expectsConfirmation method:

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