Mohamed Said's Journal

Web Developer, cyclist, and freediver.

Testing Artisan Commands in Laravel 5.7+

Posted on August, 25 2018 in Code

Testing Artisan Commands in Laravel 5.7+

Laravel 5.7 comes with a pretty neat way for testing console commands. let's see what 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')
            ->expectsQuestion('Please select a version', 'v1.0')
            ->expectsQuestion('Do you want to compile the assets?', 'yes')
            ->expectsOutput('Compiling assets...')

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 to 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.

By Mohamed Said

I work at laravelphp on weekdays and practise running, cycling, & freediving on weekends. Find me on Twitter, GitHub, and Strava.

Built Using Wink