Published Aug 2018

Testing Artisan Commands in Laravel 5.7+

Laravel 5.7 comes with a pretty neat way for testing console commands, let's see how our tests might look like:

class ArtisanCommandTest extends TestCase
{
    public function testBasicTest()
    {
        $this->artisan('nova:create', [
            'name' => 'My New Admin panel'
        ])
            ->expectsQuestion('Please enter your API key', 'apiKeySecret')
            ->expectsOutput('Authenticating...')
            ->expectsQuestion('Please select a version', 'v1.0')
            ->expectsOutput('Installing...')
            ->expectsQuestion('Do you want to compile the assets?', 'yes')
            ->expectsOutput('Compiling assets...')
            ->assertExitCode(0);
    }
}

As you can see the expectsQuestion() method asserts that a given question was asked by the Artisan Console, you need to pass the second argument which is your answer for the question for the command to continue running. If the expected question was not asked you get a descriptive error, something like:

Question "Please enter your API key" was not asked.

Also if an unexpected question was asked, you get an error:

Unexpected question "Would you like to run composer update?" was asked.

You can use the expectsQuestion assertion with all kinds of interactivity methods like confirm(), anticipate(), secret(), choice(), etc...

On the other hand, the expectsOutput() allows you to make assertions on the output of your console command, you'll get an error if an expected output was not printed by your command, however you won't receive an error on unexpected output, so it's possible for you to test your console command and ignore the output.

Finally the assertExitCode() helps you make assertions on the output of the console command.